Django多对多(m2m)与同一模型的关系 [英] Django Many-to-Many (m2m) Relation to same model

查看:89
本文介绍了Django多对多(m2m)与同一模型的关系的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想从一个用户类对象创建一个多对多的关系。

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 insead的MyUser / code>?或者还有另一种(或更好的)方法来做?

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或自我将会工作,只要它是任何一种情况下的字符串。你不能通过 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不会提醒您错误,所以有更多的机会丢失它。无论现在或将来的课程名称是什么,使用自我都会奏效。

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)与同一模型的关系的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆