Does looking at a Django model's fk_id attribute trigger a database lookup? -


i'm writing script needs go through several hundreds of thousands of models.model objects , (depending on presence or absence of blank=true, null=true foreignkey field) perform actions.

given following code:

class relateditem(models.model):    name = models.textfield()  class item(models.model):   related_item = models.foreignkey(relateditem)  items = item.objects.all() item in items:   if item.related_item:     # stuff 

i know item.related_item trigger database lookup. hoping avoid this, wondering if instead this:

items = item.objects.all()  item in items:   if item.related_item_id:     # stuff 

would item.related_item_id still trigger database call, or field stored in model, , potentially therefore run faster?

edit: note, i'm not looking use related_item, don't think need employ select_related or prefetch anything. said, if database lookups inevitable, , speed query (and not bog down machine's memory 100k items prefetched) go that.

edit 2: can't change initial queryset item.objects.all() item.objects.filter(related_item__isnull=false). example below simplification, full function needs iterate through objects in database, regardless of whether or not related_item set. understand means can't avoid database lookup on item object, i'm hoping avoid secondary lookups on item.related_item objects if don't have have them.

you can use simple way isnull

items = item.objects.filter(related_item__isnull=false) #                           ^^^^^^^^^^^^^^^^^^^^^^ item in items:     # stuff    

Comments

Popular posts from this blog

angular - Ionic slides - dynamically add slides before and after -

minify - Minimizing css files -

Add a dynamic header in angular 2 http provider -