简体   繁体   中英

Django ORM - Translate this self join query to ORM

Please help translate this SQL query to Django ORM query.

select l.* from products l inner join products r on l.category = r.category where r.id = %s

Please note that category is itself a ForeignKey that points to ProductCategory Model (telling in case it's useful for you). Also, if possible combine this with this ORM query.

Product.objects.prefetch_related('productrecipes', 'farmerprofiles', 'productfeedbacks')

Please help. Thank you.

Assuming that you want all the products from the same category as a given Product :

 # given product
 product = Product.objects.get(...)
 # products from same category
 related_products = Product.objects.filter(category_id=product.category_id)

You can then just append your prefetch_related calls:

 related_products = related_products.prefetch_related(...)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM