Analysis
Analysis

Reputation: 250

(Django) filtering objects in view

I have 2 classes in model

class A(models.Model):
    name = models.CharField(max_length = 20)
class B(models.Model):
    a = models.ForeignKey(A)

and I want to filter objects of B which does not have 'a' not has name of "exclude".

I tried

objects = B.objects.exclude(a.name == "exclude")

in my view, but it does not work.

How can I do this?

Upvotes: 0

Views: 121

Answers (2)

torm
torm

Reputation: 1546

This will work:

objects = B.objects.exclude(a__name="exclude")

Upvotes: 2

doniyor
doniyor

Reputation: 37846

objects = B.objects.exclude(a__name="exclude")

or

from django.db.models import Q
objects = B.objects.filter(~Q(a__name="exclude"))

but the former one is good enough..

Upvotes: 1

Related Questions