0

I've created a Manager for a through model and want to use it when accessing the Many-to-many objects.

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()

Manager:

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

Is there any way to access the Manager of the through field?

This here:

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

Throws:

AttributeError: 'ManyRelatedManager' object has no attribute 'active'

toni88x
  • 53
  • 2
  • 8
  • Have you tried doing this? `contact_list_entries = self.object.objects.active()`. if you want to return all contacts that are active, why don't you do `contact_list_entries = ContactList.objects.active()` – Algorithmatic Apr 23 '17 at 21:32
  • `contact_list_entries = self.object.objects.active()` doesn't work: "Manager isn't accessible via ContactList instances". I need the contact objects because they go as qs into a tables2 instance. Apparently I could do something like `[entry.contact for entry in ContactList.objects.active()]` but I thought the better way was to use a manager, since this will be a standard case and used many times. – toni88x Apr 24 '17 at 10:42

0 Answers0