Charles
Charles

Reputation: 641

ForeignKey relationship on two fields which are unique together

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

Answers (1)

willeM_ Van Onsem
willeM_ Van Onsem

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 TaillesModels 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 rename ColorModel to Color.

Upvotes: 1

Related Questions