I got pretty much the same problem as in Django - reverse query name clash.
for the following code:
class Category(models.Model):
title = models.CharField(max_length=255)
featured_product = models.ForeignKey(
'Product', on_delete=models.SET_NULL, null=True)
class Product(models.Model):
title = models.CharField(max_length=255)
price = models.DecimalField(max_digits=6, decimal_places=2)
category = models.ForeignKey(Category, on_delete=models.PROTECT)
There will be an error saying:
store.Category.featured_product: (fields.E303) Reverse query name for 'store.Category.featured_product' clashes with field name 'store.Product.category'.
I know it the featured_productin Category should addrelated_name=" " to avoid this error. But since this is a many-to-one case, and I think the reverse query name for store.Category.featured_productinProductclass should be store.Product.category_set so it shouldn't have a conflict with store.Product.category.
CodePudding user response:
Even if there weren't outright clashes (with the snippet you have, the generated reverse accessors should be Product.category_set and Category.product_set), I'd say Django is trying to be helpful so you don't make mistakes regarding the reverse accessors down the line.
As you noted, you can set related_name=' ' to not create the reverse accessor at all, but I'd probably name the reverse accessor something like related_name='featured_product_for_categories'.
After all, your data model does make it possible for a product to be featured in multiple categories, and even categories it isn't part of.
