Django Queryset across Models?

点点圈 提交于 2019-12-22 04:33:48

问题


I have several Models and want to return a queryset of all the Models belonging to a User, I'm wondering if its possible to return one Queryset from multiple Models?


回答1:


I am assuming that you mean you would like to return a single queryset of all the objects belonging to the user from each model.

Do you need a queryset or just an iterable? AFAIK, heterogeneous qs's are not possible. However, you could easily return a list, a chained iterator (itertools) or a generator to do what you want. This assumes that the models referencing the user are known ahead of time. Assuming default related_name, related queryset attributes could be accessed from user instance via the model's name:

qs = getattr(user, '%s_set' % model_name.lower());

Of course, using any heterogeneous list you would either only be able to use fields or methods that are defined across all such models, or you would have to determine the type of each object to do any type specific actions.




回答2:


Your models must contain relationship fields (ForeigKey and ManyToManyField), with related_name keyword argument set. Check documentation here.



来源:https://stackoverflow.com/questions/357425/django-queryset-across-models

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!