[英]Django ManyToMany alternative pros and cons
I was developing a chat system with channels and have this models for a thread (some attributes removed for simplicity's sake) :我正在开发一个带有频道的聊天系统,并将这个模型用于线程(为简单起见,删除了一些属性) :
class Thread(models.Model):
name = models.CharField(max_length=50, null=True, blank=True)
users = models.ManyToManyField('auth.User')
I realized it is also possible to implement it like this:我意识到也可以像这样实现它:
class Thread(models.Model):
name = models.CharField(max_length=50, null=True, blank=True)
class ThreadUsers(models.Model):
thread = models.ForeignKey(Thread, on_delete=models.CASCADE)
user = models.ForeignKey(User, on_delete=models.CASCADE)
What are the advantages/disadvantages of using one over the other?使用其中一种的优点/缺点是什么?
All what you do - is the same.你所做的一切——都是一样的。 For your last example with custom M2M through model you can add M2M declaration users
in Thread:对于通过 model 自定义 M2M 的最后一个示例,您可以在线程中添加 M2M 声明users
:
class Thread(models.Model):
name = models.CharField(max_length=50, null=True, blank=True)
# M2M declaration, which use your ThreadUsers
users = models.ManyToManyField('auth.User', through='ThreadUsers' )
class ThreadUsers(models.Model):
thread = models.ForeignKey(Thread, on_delete=models.CASCADE)
user = models.ForeignKey(User, on_delete=models.CASCADE)
Pros:优点:
we have in our projects 50/50 M2M-autothrough vs M2M-manualthrough.我们的项目中有 50/50 M2M-autothrough 与 M2M-manualthrough。 if I want to have more control on the models and realations - i use custom through.如果我想对模型和现实有更多的控制 - 我使用自定义。
ps in M2M-autothrough case Django created SomethingLikeYourThreadUsers Model and Table automatically. ps 在 M2M-autothrough 案例 Django 中自动创建了 SomethingLikeYourThreadUsers Model 和 Table。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.