Reputation: 641
I'd like to make a relationship like so in django:
class ColorModel(models.Model):
article = models.ForeignKey(ArticleModel, to_field='name', on_delete=models.CASCADE)
color = models.CharField(max_length=10)
class Meta:
unique_together = ('article', 'color')
class TaillesModel(models.Model):
article = models.ForeignKey(ColorModel, on_delete=models.CASCADE)
color = models.ForeignKey(ColorModel, on_delete=models.CASCADE)
size = models.CharField(max_length=10)
quantity = models.IntegerField()
So each article has multiple colors, and each of those colors has multiple sizes in different quantities.
However, this gives me those errors:
Reverse accessor for 'TaillesModel.article' clashes with reverse accessor for 'TaillesModel.color'.
HINT: Add or change a related_name argument to the definition for 'TaillesModel.article' or 'TaillesModel.color'.
front.TaillesModel.color: (fields.E304) Reverse accessor for 'TaillesModel.color' clashes with reverse accessor for 'TaillesModel.article'.
HINT: Add or change a related_name argument to the definition for 'TaillesModel.color' or 'TaillesModel.article'.
I don't understand what related_name
is supposed to be set to here.
Thanks in advance for your help.
Upvotes: 1
Views: 59
Reputation: 476659
The related_name=…
parameter [Django-doc] is the name of the relation in reverse. So it means that for a given ColorModel
object, you can access the TaillesModel
s that refer to that ColorModel
through the article
model, or the color
model. By default these are given the name modelname_set
, so in this case colormodel_set
, but since there are two of them, that would clash.
You thus should define two different names, for example:
class TaillesModel(models.Model):
article = models.ForeignKey(
ColorModel,
on_delete=models.CASCADE,
related_name='tailles_as_articlecolor'
)
color = models.ForeignKey(
ColorModel,
on_delete=models.CASCADE,
related_name='tailles_as_color'
)
size = models.CharField(max_length=10)
quantity = models.IntegerField()
Note: Models normally have no
Model
suffix. Therefore it might be better to renametoColorModel
Color
.
Upvotes: 1