My django model joining wrong fields when there are multiple related fields with join

37 views
Skip to first unread message

Sadaf Noor

unread,
Sep 20, 2018, 12:20:17 AM9/20/18
to Django users

My product model has two different relationship with category model:

  1. One to One
  2. One to Many through ProductShadowCategory table.

Now the situation is when I tried to fetch using the second relationship, I am getting the result from my first relationship.

For example this is what I am trying to print:

Category.objects.get(slug="root").shadow_products.all()

but it converts to following sql :

print(Category.objects.get(slug="root").shadow_products.all().query)

SELECT `product_management_product`.`id`, `product_management_product`.`slug`, `product_management_product`.`category_id`, `product_management_product`.`brand_id` FROM `product_management_product` WHERE `product_management_product`.`category_id` = 720

My models looks like following:

class Category(SlugableModel):
    #...
    shadow_products = models.ManyToManyField("product_management.Product", through="product_management.ProductShadowCategory")

class Product(SlugableModel):
    #...
    category = models.ForeignKey(Category,on_delete=models.CASCADE, related_name="products", validators=[leaf_category])

class ProductShadowCategory(MyModel):
    category = models.ForeignKey(Category,on_delete=models.CASCADE)
    product = models.ForeignKey(Product,on_delete=models.CASCADE)

    class Meta:
        unique_together = ('category', 'product')
Also asked on stackoverflow: https://stackoverflow.com/questions/52417494/my-django-model-joining-wrong-fields-when-there-are-multiple-related-fields-with
--



 
 Md. Sadaf Noor (@sadaf2605)
 www.sadafnoor.me

luca bocchi

unread,
Sep 25, 2018, 6:25:53 PM9/25/18
to Django users
Hi Sadaf,
re the m2m rel:
since your not adding additional fields on the intermediate model ProductShadowCategory, there's no need for that:

class Category(SlugableModel):
    shadow_products = models.ManyToManyField("product_management.Product")

the orm will automatically create an intermediate table containing the pks of Category and Product.

I dont understand the issue:

Now the situation is when I tried to fetch using the second relationship, I am getting the result from my first relationship.

please provide more details and what you're trying to achieve, 

thanks
Reply all
Reply to author
Forward
Message has been deleted
0 new messages