0

I have a "ModelVoiture" model with a foreign key "type_carburant" field and I can access the "typeCarburant" field of the "Carburant" model. I need to access another field of the same model "Carburant", the field "prixCarburant" from the model "ModelVoiture" but if I add the line

prixCarburant = models.ForeignKey(Carburant, on_delete=models.CASCADE)

i have this error

coutcarbur.ModelVoiture.prixCarburant: (fields.E304) Reverse accessor 'Carburant.modelvoiture_set' for 'coutcarbur.ModelVoiture.prixCarburant' clashes with reverse accessor for 'coutcarbur.ModelVoiture.typeCarburant'.
        HINT: Add or change a related_name argument to the definition for 'coutcarbur.ModelVoiture.prixCarburant' or 'coutcarbur.ModelVoiture.typeCarburant'.
coutcarbur.ModelVoiture.typeCarburant: (fields.E304) Reverse accessor 'Carburant.modelvoiture_set' for 'coutcarbur.ModelVoiture.typeCarburant' clashes with reverse accessor for 'coutcarbur.ModelVoiture.prixCarburant'.
        HINT: Add or change a related_name argument to the definition for 'coutcarbur.ModelVoiture.typeCarburant' or 'coutcarbur.ModelVoiture.prixCarburant'.

my code in coutcarbur/models.py

class MarqueVoiture(models.Model):
    name = models.CharField(max_length=50)

    def __str__(self):
        return self.name


class Carburant(models.Model):
    name = models.CharField(max_length=50)
    prixCarburant = models.DecimalField(max_digits=6, decimal_places=2)
    typeCarburant = models.CharField(max_length=50)

    def __str__(self):
        return self.name


class ModelVoiture(models.Model):
    name = models.CharField(max_length=50)
    consolitre = models.DecimalField(
        max_digits=6, decimal_places=2)
    prixCarburant = models.ForeignKey(Carburant, on_delete=models.CASCADE)
    typeCarburant = models.ForeignKey(Carburant, on_delete=models.CASCADE)    
    marque = models.ForeignKey(MarqueVoiture, on_delete=models.CASCADE)

    def __str__(self):
        return self.name

how to implement related_name function in template to solve this problem. I must surely revise the diagram of my models?

thanks for any help.

Zembla
  • 331
  • 1
  • 2
  • 9
  • 1
    https://stackoverflow.com/a/44398542/16537039 – Patryk Laszuk Sep 01 '22 at 09:17
  • thank , i try this solution in "ModelVoiture" model : prixCarburant = models.ForeignKey(Carburant, on_delete=models.CASCADE,related_name='prixCarburant_carburant') typeCarburant = models.ForeignKey(Carburant, on_delete=models.CASCADE,related_name='typeCarburant_carburant') but now the foreign key in "prixCarburant" field have same target of "typeCarburant" of "Carburant" model – Zembla Sep 01 '22 at 10:06
  • finally I realized that I do not need to link the "TypeCarburant" fields of the "Carburant" model to "modelVoiture" models. not thought enough about the design of the models. sorry for the disturbance. Anyway, if anyone has a solution to the original question that would be a bonus. – Zembla Sep 01 '22 at 17:40

0 Answers0