Django:在ManytoMany中访问额外字段(通过=)

时间:2019-07-16 15:06:13

标签: python django

我正在尝试访问purchaser字段中的ManytoMany字段。我使用through=添加了一些额外的字段。但是,看来我只能访问事件对象,而不能访问额外的字段。有人可以向我解释原因吗?

for selected_order in Order.objects.all():
    contact_exists = Contact.objects.filter(
        email=selected_order.email,
        event_related_fields=selected_order.event,
    )
    if contact_exists:
        contact = contact_exists.first()
        for x in contact.event_related_fields.all():
            print(x.purchaser)

models.py

class Contact(TimeStampedModel):
    consent = models.BooleanField(verbose_name=_("Consent"))
    email = models.EmailField(verbose_name=_("Your email"))
    first_name = models.CharField(
        max_length=100,  # TODO Length must be same as for billing model
        verbose_name=_("First name"),
        null=True,
        blank=True,
    )
    last_name = models.CharField(
        max_length=100,  # TODO Length must be same as for billing model
        verbose_name=_("Last name"),
        null=True,
        blank=True,
    )
    events = models.ManyToManyField(Event, related_name='contacts')
    event_related_fields = models.ManyToManyField(
        Event, related_name='event_related_fields', through='EventRelatedFields'
    )
    organizer = models.ForeignKey(
        Organizer, on_delete=models.PROTECT, related_name='contacts'
    )  # PROTECT = don't allow to delete the organizer if contact exists

    class Meta:
        verbose_name = _("Contact")
        verbose_name_plural = _("Contacts")
        ordering = ('created',)
        unique_together = ('email', 'organizer')

    def __repr__(self):
        return "{}: {}".format(self.__class__.__name__, self)

    def __str__(self):
        return self.email


class EventRelatedFields(TimeStampedModel):
    event = models.ForeignKey(Event, on_delete=models.CASCADE)
    contact = models.ForeignKey(Contact, on_delete=models.CASCADE)
    lead = models.BooleanField(
        verbose_name='Lead', default=False
    )  # Contact who 'Signed Up'
    attendee = models.BooleanField(
        verbose_name='Attendee', default=False
    )  # Contact assigned to ticket
    purchaser = models.BooleanField(
        verbose_name='Purchaser', default=False
    )  # Contact made the order

    class Meta:
        unique_together = [['event', 'contact']]

1 个答案:

答案 0 :(得分:2)

由于某种原因,您正在定义两个多对多关系,并且已经使用相同的相关名称调用了其中一个event_related_fields。结果,您将其与穿透表混淆了。但是由于穿透表实际上称为EventRelatedFields,因此您可以将其相关对象作为eventrelatedfields_set来访问。

您只能有一个平方米,events

events = models.ManyToManyField(Event, through='EventRelatedFields', related_name='contacts')

,您的类EventRelatedFields本身应设置相关名称:

event = models.ForeignKey(Event, related_name='event_related_fields', on_delete=models.CASCADE)
contact = models.ForeignKey(Contact, related_name='event_related_fields, on_delete=models.CASCADE)

现在您可以这样做:

for x in contact.event_related_fields.all():
    print(x.purchaser)