Ivan Pereira
Ivan Pereira

Reputation: 2239

Django test NULL field without hit database

I have the following schema:

class A(models.Model):
    name = models.CharField(max_length=100)

class B(models.Model):
    name = models.CharField(max_length=100)
    a = models.ForeignKey(A, blank=True, null=True)

Picking up all B objects to template

b = B.objects.all()

In the template i want to go

for n in b:
    n.name
    if n.a:
        do_something()

But this is hitting the database because of the Foreign Key, and i only want to know if a is null or not. And i dont want to fetch all A stuff with a join.

Upvotes: 0

Views: 153

Answers (1)

Ngenator
Ngenator

Reputation: 11269

When you create a relationship to another model, behind the scenes django is actually using a field called a_id to locally store the id of the A model on the B model (it also creates the id behind the scenes). Then when you access b.a it knows which A to select based off of the actual database entry in the B table.

So:

b.a follows the relationship and hits the database to get the A model

b.a_id uses the local b model's field that contains the id that relates to the A model

Let me know if that doesn't make sense...

Upvotes: 4

Related Questions