通过模型了解Django中的ManyToMany字段

通过模型了解Django中的ManyToMany字段

本文介绍了通过模型了解Django中的ManyToMany字段的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我无法理解具有贯通模型的ManyToMany模型字段的使用。没有ManyToMany字段,我可以轻松实现相同目标。考虑以下来自Django文档的信息:

I'm having trouble understanding the use of ManyToMany models fields with a through model. I can easily achieve the same without the ManyToMany field. Considering the following from Django's docs:

class Person(models.Model):
    name = models.CharField(max_length=128)


class Group(models.Model):
    name = models.CharField(max_length=128)
    members = models.ManyToManyField(Person, through='Membership')


class Membership(models.Model):
    person = models.ForeignKey(Person, on_delete=models.CASCADE)
    group = models.ForeignKey(Group, on_delete=models.CASCADE)
    date_joined = models.DateField()
    invite_reason = models.CharField(max_length=64)

我不了解的是,如何使用ManyToMany字段比简单地删除它并使用相关的管理器要好。例如,两个模型将更改为以下内容:

What I don't understand, is how is using the ManyToMany field better than simply dropping it and using the related manager. For instance, the two models will change to the following:

class Group(models.Model):
    name = models.CharField(max_length=128)


class Membership(models.Model):
    person = models.ForeignKey(Person, on_delete=models.CASCADE)
    group = models.ForeignKey(Group, on_delete=models.CASCADE, related_name='members')
    date_joined = models.DateField()
    invite_reason = models.CharField(max_length=64)

我在这里缺少什么?

推荐答案

是的,使用显式的 through 表基本上消除了对 ManyToManyField 的需求。

Yes, using an explicit through table basically eliminates the need for a ManyToManyField.

拥有它的唯一真正优势是,如果您发现相关的经理方便。即:

The only real advantage to having it is if you'd find the related manager convenient. That is, this:

group.members.all()  # Persons in the group

看起来比这个更好:

Person.objects.filter(membership_set__group=group)  # Persons in the group

实际上,我认为主要两者都有的原因是人们通常以简单的 ManyToManyField 开始;意识到他们需要一些其他数据,并添加一个表;然后由于使用了同时使用两个管理器的代码而最终两者兼而有之。

In practice, I think the main reason for having both is that often people start with a plain ManyToManyField; realize they need some additional data and add a through table; and then end up with both due to code that uses both managers.

这篇关于通过模型了解Django中的ManyToMany字段的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-03 10:11