如何通过模型访问Manager

时间:2017-04-23 20:48:26

标签: django many-to-many django-managers

我为直通模型创建了一个Manager,并希望在访问多对多对象时使用它。

class Contact(models.Model):
    first_name = models.CharField(max_length=50, null=True, blank=True)
    last_name = models.CharField(max_length=50, null=True, blank=True)
    email = models.EmailField()

class ContactList(models.Model): 
    name = models.CharField(max_length=50)
    contacts = models.ManyToManyField(
        Contact,
        through='ContactListEntry',
        blank=True,
    )


class ContactListEntry(models.Model):
    contact_list = models.ForeignKey(ContactList, related_name='contact_list_entries')
    contact = models.ForeignKey(Contact, related_name='contact_list_entries')
    removed = models.BooleanField(default=False)  # Used to avoid re-importing removed entries.

    # Managers.
    objects = ContactListEntryManager()

管理器:

class ContactListEntryManager(Manager):
    def active(self):
        return self.get_queryset().exclude(removed=True)

有没有办法访问直通领域的经理?

这里:

class ContactListView(DetailView):
    model = ContactList
    template_name = 'contacts/contact_list.html'
    context_object_name = 'contact_list'

    def get_context_data(self, **kwargs):
        ctx = super(ContactListView, self).get_context_data(**kwargs)
        contact_list_entries = self.object.contacts.active()  # <-- THIS HERE.
        ctx.update({
            "contact_list_entries": contact_list_entries,
        })
        return ctx

抛出:

  

AttributeError:'ManyRelatedManager'对象没有属性'active'

0 个答案:

没有答案