0👍
✅
On a different note, why don’t you just read the whole querysets (for MyModel
and MyOtherModel
) into memory and then compare? Would be efficient in terms of number of queries to db
m_rows = MyModel.objects.filter(...)
m = m_rows.order_by('myField').values_list('myField')
m_set = set([x for x in m])
mo_rows = MyOtherModel.objects.all()
mo = mo_rows.values_list('myOtherField')
mo_set = set([x for x in mo])
common = list(m_set.intersection(mo_set))
mo_result = MyOtherModel.objects.filter(myOtherField__in=common).order_by('myOtherField')
for i in range(len(mo_result)):
print("{:s}{:s}".format(m_rows[i], mo_rows[i]))
I believe this is overly complicated and there should be a better way to do this.
But this saves you n queries to db.
0👍
There are some points:
1- If these queries will run in an operational system with large data by a user request, you need to redesign your ER model or consider other solutions.
2-If you don’t have a lack of memory problem, you can load your whole objects of the models in memory with two queries.
MyOtherModelAll=MyOtherModel.objects.all()
for m in MyModel.objects.filter(...):
for mo in MyOtherModelAll:
if(mo.myOtherField=m.myField)
print("{:s}{:s}".format(m, mo))
3. Annotate method tells Django to add an extra attribute to every object returned.The following sample me be usefull for you:
Book.objects.annotate(search=searchVector ('title','abstract'),).filter(search='django')
👤Azdy
- [Django]-Virtualenv, sys.path and site-packages
- [Django]-Issue with returning Cyrillic symbols from MSSQL via unixODBC and FreeTDS
- [Django]-Django creates the test database for Postgresql with incorrect sequences start values
- [Django]-Explicitly clear django memcached flush/cache() OR delete specific per-view-cache key
- [Django]-Hiding save buttons in admin if all fields are read only
Source:stackexchange.com