Alfredo Solís
Alfredo Solís

Reputation: 458

queryset django relationship

I have two models:

class Income(models.Model):
    id = models.AutoField('ID', primary_key=True)
    date = models.DateField('Date', blank=True, null=True)
    user = models.ForeignKey(User, null=True, help_text="User Income")

class Invoice(models.Model):
    id = models.AutoField('ID', primary_key=True)
    income = models.ForeignKey(Income, null=True, blank=True, related_name='Income')
    user = models.ForeignKey(User, null=True, blank=True, related_name='User_Invoice')

and I need to get the "Income" that are not associated with any "Invoice". I find no way to see this problem. Thank you very much :)

Upvotes: 1

Views: 354

Answers (1)

Peter DeGlopper
Peter DeGlopper

Reputation: 37319

Filter using __isnull:

Normally, Django automatically follows relationship fields using the lowercased name of the related model:

Income.objects.filter(invoice__isnull=True)

Here, you've specified the related_name attribute, so you need to use that:

Income.objects.filter(Income__isnull=True)

Note that this reveals that your related name attribute for the income FK on Invoice is backwards. I see no reason for you to be setting a related_name at all, but if you do need one it should describe how the invoices are related to incomes, not vice versa.

Upvotes: 1

Related Questions