Bacon
Bacon

Reputation: 2195

tell django not to follow foreign key?

Is there a way to tell django not to follow a foreign key relationship when you instantiate a model instance? Something to put on the model itself? Something to pass to a queryset? I'd like to have a queryset that only returns instances with the foreign key id -- I don't want the instances to go off making queries to find its relatives. Something like the opposite of select_related?

Upvotes: 1

Views: 459

Answers (2)

bradley.ayers
bradley.ayers

Reputation: 38382

The default behaviour of Django is to wait until a foreign key relationship is accessed before performing a database queries to populate the related model instance.

To side-step the automatic querying for related instances, rather than accessing the ForeignKey field attribute directly, access attribute_id, e.g.

class Person(models.Model):
    name = models.CharField(max_length=200)
    user = models.ForeignKey('auth.User')

# access the user id via user_id
person = Person.objects.all()[0]
print person.user_id

Upvotes: 4

Dmitry Shevchenko
Dmitry Shevchenko

Reputation: 32404

Try defer

Upvotes: 0

Related Questions