Frage

I'm trying to make a new list of unused/unselected objects, so that I can show in the template what is used, and what is not used.

My model:

class Benefit(models.Model):
    name = models.CharField(max_length=200)

class Profile(models.Model):
    benefits = models.ManyToManyField(Benefit, blank=True, null=True, related_name="used_benefit")

My view:

class Profile(TemplateView):
    template_name = "profile/benefits.html"

    def get_context_data(self, **kwargs):
            context = super(Profile, self).get_context_data(**kwargs)
            context['unused_benefits'] = Profile.objects.exclude(pk__in=Profile.benefits.all())
            return context

It is something Im not getting, because I get this error: 'ReverseManyRelatedObjectsDescriptor' object has no attribute 'all'

I have tried without all, but then I get the error 'ReverseManyRelatedObjectsDescriptor' object is not itterable

Anyone see what I'm doing wrong?

War es hilfreich?

Lösung

What you're doing doesn't make any sense at all. You can't access benefits.all() on the Profile class itself, only on an instance of it. What would Profile.benefits.all() even mean?

And even if that did work, that would give you a list of Benefits. How could you then use that to exclude Profiles by pk? And then, thirdly, how would that Profile query help you get a list of unused benefits?

If you are trying simply to get a list of Benefits that have no Profiles attached to them, then you actually need to query the Benefits model, not Profile:

unused_benefits = Benefits.objects.filter(profile__isnull=True)
Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top