Tuesday, September 25, 2018

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

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

Il giorno giovedì 20 settembre 2018 06:20:17 UTC+2, Sadaf Noor ha scritto:

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

--
You received this message because you are subscribed to the Google Groups "Django users" group.
To unsubscribe from this group and stop receiving emails from it, send an email to django-users+unsubscribe@googlegroups.com.
To post to this group, send email to django-users@googlegroups.com.
Visit this group at https://groups.google.com/group/django-users.
To view this discussion on the web visit https://groups.google.com/d/msgid/django-users/2fe141a7-3e2d-4653-a778-5ce1539d5f89%40googlegroups.com.
For more options, visit https://groups.google.com/d/optout.

No comments:

Post a Comment