Lei Xu
Lei Xu

Reputation: 11

django two column foreign key reference to one column

class Personal(models.Model):
    Personal_ID = models.SmallIntegerField(primary_key=True)
    Name = models.CharField(max_length=20)
    
    class Meta:
        managed = True
        db_table = 'Personal'

class Tests(models.Model):
    
    Requestor = models.ForeignKey('Personal',models.DO_NOTHING,
    db_column='Personal_ID')
    Analyst = models.ForeignKey('Personal', on_delete=models.CASCADE,db_column='Personal_ID',related_name='+')
   
    class Meta:
        managed = True
        db_table = 'Tests'

I have this problem, I have two columns foreigner key and reference one columns, which works in mysql, but it did not work in Django models. it showed there are two same db_columns in one models and it is not allowed, how to fix it. I will appreciate it

here is the code. how to avoid to use one db_column twice?

Upvotes: 0

Views: 1843

Answers (2)

Moses Charles
Moses Charles

Reputation: 56

Documentation says: "The name of the database column to use for this field. If this isn’t given, Django will use the field’s name."

Your model has db_column=Personal_ID on two fields. This means that you want to name two fields Personal_ID. There should be no duplicate column names; each column must have a unique name.

The solution is to remove db_column=Personal_ID from one of the fields, then the other field can have db_column=Another_Personal_ID

https://docs.djangoproject.com/en/4.0/ref/models/fields/

Upvotes: 0

Nikita Kosych
Nikita Kosych

Reputation: 121

db_column = The name of the database column to use for this field. If this isn’t given, Django will use the field’s name.

Either remove the db_column from both of them, or set them to a different value.

Upvotes: 1

Related Questions