问题描述
我想在用户类对象之间创建多对多关系.
I'd like to create a many-to-many relationship from and to a user class object.
我有这样的事情:
class MyUser(models.Model):
...
blocked_users = models.ManyToManyField(MyUser, blank=True, null=True)
问题是我是否可以在其内部使用类引用.或者我必须在 ManyToManyField
中使用 "self"
代替 "MyUser"
吗?或者还有其他(更好)的方法吗?
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"会起作用,只要它在任何一种情况下都是字符串.你只是不能通过 MyUser
,实际的类.
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.
然而,文档总是使用self".使用self"不仅可以更明确地说明实际发生的事情,而且不受类名更改的影响.例如,如果您稍后将 MyUser
更改为 SomethingElse
,那么您还需要更新对MyUser"的任何引用.问题在于,由于它是一个字符串,因此您的 IDE 不会提醒您注意错误,因此您错过它的可能性更大.无论类现在或将来的名称是什么,使用self"都可以.
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.
这篇关于Django 多对多 (m2m) 与同一模型的关系的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!