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
?
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
Try defer
精彩评论