'Limit Django filter query set by a N number of field

I think I cannot well express myself with words so I can put some code so you can understand me better

I have a model

class Obj(models.Model):
  foo = models.IntegerField()

Then I have 8 objects where.

obj1.foo = 1
obj2.foo = 1
obj3.foo = 1
obj4.foo = 2
obj5.foo = 2
obj6.foo = 2
obj7.foo = 3
obj8.foo = 3

With the query set

objs = Obj.objects.all()
obj = QuerySet[obj1, obj2, obj3, obj4, obj5, obj6, obj7, obj8]

Then the query that I want is limit the obj by foo

filtered_obj = QuerySet[
 obj1,  # foo=1
 obj2,  # foo=1
 obj4,  # foo=2
 obj5,  # foo=2
 obj7,  # foo=3
 obj8.  # foo=3
]

I don't want repeated fields more than 2 times.



Solution 1:[1]

Use Filter instead of all and pass foo as param

obqs = Obj.objects.filter(foo=1)[:2]
# returns QuerySet[obj1, obj2]
obqs = Obj.objects.filter(foo=3)[:2]
# returns  QuerySet[obj7, obj8]

Refer Django Docs

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1