Good day. I started practicing with django, I found an old saytik of automotive topics, I decided to re-create it in jang. I came across such a problem: there are several models

class CarsParametrTypes(models.Model): title = models.CharField(max_length = 100,verbose_name = 'Название') def __str__(self): return self.title class Meta: verbose_name = 'Параметры' verbose_name_plural = 'Параметры' db_table = 'catalog_cars_parametr_type' class CarsParametrValues(models.Model): type = models.ForeignKey(CarsParametrTypes,verbose_name = 'Параметр') value = models.CharField(max_length = 100, verbose_name = 'Значение') def __str__(self): return self.value class Meta: verbose_name = 'Значение' verbose_name_plural = 'Значения' db_table = 'catalog_cars_parametr_values' 

I want all parameter values ​​to be stored in one table for example for CarsParametrTypes such records as Condition, Drive, type of fuel

Next, create a model Cars

  class Cars(models.Model): model = models.CharField(max_length=50, verbose_name='Модель') color = models.CharField(max_length=50, verbose_name='Цвет') probeg = models.IntegerField(default = 0, verbose_name = 'Пробег') year = models.IntegerField(default = 0, verbose_name = 'Год выпуска') power = models.IntegerField(default = 0, verbose_name = 'Мощность, л.c.') drive = models.ForeignKey(CarsParametrValues, verbose_name = 'Привод', limit_choices_to={'type_id': 1}) 

In this form, everything works, but if I add one more field, for example:

 fuel = models.ForeignKey(CarsParametrValues, verbose_name = 'Тип топлива', limit_choices_to={'type_id': 2}) 

Then when creating a migration, an error occurs. Attempts to google the solution did not lead to success: in all the considered examples, the connections (I also tried not to indicate the ForeignKey , but ManaToMany ) do not apply twice or more to the same model.

  • And why was it even necessary to determine the connection to the same table twice? - Mr Fix
  • As for me, it’s logical. You can create a separate table for each parameter, for example, a gearbox, but there will be only a few entries in it. And such parameters can be 5-10 And so 2 tables of type and values - Georgii Baruchyan
  • Well, one thing is to connect two tables, and the other two times one table. - Mr Fix

1 answer 1

When using multiple ForeignKey to the same model, they must have different values related_name

Those. in your case it should be something like this:

 drive = models.ForeignKey(CarsParametrValues, verbose_name = 'Привод', limit_choices_to={'type_id': 1}, related_name='drive_params') fuel = models.ForeignKey(CarsParametrValues, verbose_name = 'Тип топлива', limit_choices_to={'type_id': 2}, related_name='fuel_params') 

Read more about this in the Django documentation: here , here and here .