Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 234
khue bui Avatar asked Feb 03 '26 15:02

khue bui


1 Answers

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,

like image 194
Exprator Avatar answered Feb 05 '26 07:02

Exprator



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!