[Answered ]-How can I combine 2 django query into one with object limit

2👍

Have you tried searching with a list user __in. So construct a list of the things you want to filter.

Search_model.objects.filter(obj_type__in=["mall", "store"], city=city)

See: https://docs.djangoproject.com/en/1.11/ref/models/querysets/#in

0👍

If it’s Postgres, you can use ROW_NUMBER along with raw sql:

Search_model.objects.raw("SELECT id, obj_type from (
        SELECT t.*, ROW_NUMBER() OVER (PARTITION BY obj_type) AS rn 
        FROM search_model t
    ) WHERE rn < 3 and obj_type in ('mall', 'store')"
);

Would not prefer this way, as last I checked sqlite3 has no ROW_NUMBER.

For SqlLite3 you can fire:

SELECT id, obj_type
FROM search_model t1 
WHERE id in ( 
   select id from search_model t2 
   where t2.obj_type = t1.obj_type 
   order by t2.obj_type desc limit 2
) 
ORDER BY id, obj_type DESC;

With Django ORM, we might look into, Internally, a QuerySet can be constructed, filtered, sliced, and generally passed around without actually hitting the database:

from django.db.models import Q

mall_items = Search_model.objects.filter(obj_type="mall", city=city).values_list("id", flat=True)[:2]
store_items = Search_model.objects.filter(obj_type="store", city=city).values_list("id", flat=True)[:2]

print Search_model.objects.filter(Q(id__in=mall_items)|Q(id__in=store_items))

Leave a comment