Orca
Orca

Reputation: 2025

Django: Exclude all rows of a table that have links in another Table

I have two tables in my models.py, and I want to return all results from table A that have a certain slug value AND don't appear as a foreign key in table B.

My tables as in models.py:

class ModelA(models.Model):
    slug = models.SlugField()
    title = models.CharField(max_length=100)

class ModelB(models.Model):
    modela = models.ForeignKey(ModelA)
    amount = models.CharField(max_length=10)

What is the way in views.py to return all the rows in ModelA that have the same slug ( like ModelA.objects.filter(slug=slug) ) and that don't have any links to ModelB.

Thanks

Upvotes: 1

Views: 922

Answers (1)

Timmy O'Mahony
Timmy O'Mahony

Reputation: 53998

You should be able to use filter with isnull:

>>> ModelA.objects.filter(slug__iexact="foo", modelb__isnull=True)

Upvotes: 4

Related Questions