I'd like to create a many-to-many relationship from and to a user class object.
我想创建一个用户类对象之间的多对多关系。
I have something like this:
我有这样的东西:
class MyUser(models.Model):
...
blocked_users = models.ManyToManyField(MyUser, blank=True, null=True)
The question is if I can use the class reference inside itself. Or do I have to use "self"
insead of "MyUser"
in the ManyToManyField
? Or is there another (and better) way to do it?
问题是我是否可以在类内部使用类引用。还是说,我必须在许多领域使用“MyUser”的“self”insead ?或者还有其他更好的方法吗?
2 个解决方案
#1
43
Technically, I'm pretty sure "MyUser" or "self" will work, as long as it's a string in either case. You just can't pass MyUser
, the actual class.
从技术上讲,我很确定“MyUser”或“self”会起作用,只要它在任何情况下都是字符串。你不能通过MyUser,实际的类。
However, the docs always use "self". Using "self" is not only more explicit about what's actually happening, but it's impervious to class name changes. For example, if you later changed MyUser
to SomethingElse
, you would then need to update any reference to "MyUser" as well. The problem is that since it's a string, your IDE will not alert you to the error, so there's a greater chance of your missing it. Using "self" will work no matter what the class' name is now or in the future.
但是,文档总是使用“self”。使用“self”不仅可以更清楚地了解实际发生的事情,而且不受类名更改的影响。例如,如果稍后将MyUser更改为SomethingElse,则还需要更新对“MyUser”的任何引用。问题是,由于它是一个字符串,您的IDE将不会提醒您错误,所以您很可能会错过它。无论类的名称是现在还是将来,使用“self”都是可行的。
#2
26
class MyUser(models.Model):
...
blocked_users = models.ManyToManyField("self", blank=True)
#1
43
Technically, I'm pretty sure "MyUser" or "self" will work, as long as it's a string in either case. You just can't pass MyUser
, the actual class.
从技术上讲,我很确定“MyUser”或“self”会起作用,只要它在任何情况下都是字符串。你不能通过MyUser,实际的类。
However, the docs always use "self". Using "self" is not only more explicit about what's actually happening, but it's impervious to class name changes. For example, if you later changed MyUser
to SomethingElse
, you would then need to update any reference to "MyUser" as well. The problem is that since it's a string, your IDE will not alert you to the error, so there's a greater chance of your missing it. Using "self" will work no matter what the class' name is now or in the future.
但是,文档总是使用“self”。使用“self”不仅可以更清楚地了解实际发生的事情,而且不受类名更改的影响。例如,如果稍后将MyUser更改为SomethingElse,则还需要更新对“MyUser”的任何引用。问题是,由于它是一个字符串,您的IDE将不会提醒您错误,所以您很可能会错过它。无论类的名称是现在还是将来,使用“self”都是可行的。
#2
26
class MyUser(models.Model):
...
blocked_users = models.ManyToManyField("self", blank=True)