Django spanning relationships

无人久伴 提交于 2019-12-04 05:42:45

If you need users, you should start with users. Also, you need to filter on a specific field in Annual, ie year_id.

User.objects.filter(order__select__annual__year_id=2014)

If I got your question correctly then, your query is wrong. There is no attribute name order inside your Catalog model, then how can you use it for filtering ? Or I'm missing anything here ?

Directly using the related name references on the related fields, you can get the users by using -

# id is auto generated field or you can pass one annual_product object.
User.objects.filter(who_ordered__select__annual_products__id=1)

# OR
annual = Annual.objects.all()[0]
User.objects.filter(who_ordered__select__annual_products=annual)

The step by step how you can achieve the same :-

# where 1 is the id of an one object in Catalog model.
# You can pass Catalog object also to filter the users
Order.objects.filter(select__id=1)

# Here is the full query 
catalog = Catalog.objects.all()[0]
orders = Order.objects.filter(select=catalog)
users = [o.user for o in orders]  # This loop isn't necessary.

Now you have all orders specific to one Catalog, from this you can get the user object by using the user attribute in each order.

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