khue bui
khue bui

Reputation: 1416

Django filter limit objects

sorry for the stupid question.

I don't know where to find this solution or any keyword reference for it.

Let say, I have 2 models Place and Tips, and:

# list of place id
place_id_list = [...]

How do I filter tips over the place_id_list that just retrieve <= 5 tips object for every place

Here is the model:

class Place:
   ...
class Tip:
  # object_id is id of place
  object_id = models.PositiveIntegerField(editable=False)
  content_type = models.ForeignKey(ContentType)

Right now, I just use for loop like:

tip_list = []    
for place_id in place_id_list:
    tip_list += Tip.objects.filter(object_id=place_id, content_type...)[0:5]

But this query seem to slow.

Is there any better solution?

Thanks.

Upvotes: 3

Views: 7773

Answers (2)

Sathish Kumar VG
Sathish Kumar VG

Reputation: 2172

Try with below query:

tip_list =Tip.objects.filter(object_id__in=place_id_list, content_type...)[:5]

Reference link:

https://docs.djangoproject.com/en/dev/topics/db/queries/#the-pk-lookup-shortcut

Upvotes: 2

Exprator
Exprator

Reputation: 27503

tip_list = []    
for place_id in place_id_list:
    tip_list += Tip.objects.filter(object_id=place_id, content_type...)[:5]

there is no better way than this, as you know django is lazy loader and doesnt hit the database unless a new object is needed,

Upvotes: 8

Related Questions