Reputation: 155
In many to many relationships with the intermediate table, I use multiple foreign keys. but got error like The model is used as an intermediate model by 'examples.Employee.designation', but it has more than one foreign key from 'Employee', which is ambiguous. You must specify which foreign key Django should use via the through_fields keyword argument my models are with intermediate table
class Employee(models.Model):
code = models.CharField(max_length = 256)
designation =models.ManyToManyField(Designation,related_name='+',through = 'HRManagement',blank=True)
status = models.BooleanField(default = True)
join_date = models.DateField(default=datetime.datetime.now)
leave_date = models.DateField(blank = True, null=True)
username = models.CharField(max_length = 256)
password = models.CharField(max_length = 256)
first_name = models.CharField(max_length = 256)
last_name = models.CharField(max_length = 256)
address = models.TextField()
class Designation(models.Model):
name = models.CharField(max_length = 256)
class HRManagement(models.Model):
employee = models.ForeignKey(Employee, related_name = 'employee', null=True,on_delete=models.CASCADE)
designation = models.ForeignKey(Designation, on_delete=models.CASCADE,default=None,null=True)
reportto = models.ForeignKey(Employee, null=True, related_name='reportto',on_delete=models.CASCADE)
how could I fix this error? please help me in models building
Upvotes: 2
Views: 954
Reputation: 131
The through model (HRManagement
) contains two ForeignKey
s to the same model (Employee
being linked to by both employee
and reportto
), which is ambiguous. This is what through_fields
is for.
Try adding through_fields=('employee', 'designation')
to designation
so that the field is declared as:
designation = models.ManyToManyField(Designation, related_name='+', through='HRManagement', blank=True, through_fields=('employee', 'designation'))
As a different answer in a different question points out, the order of the fields in through_fields
is (source, destination)
. If swapped, makemigrations
errors out with E339.
Upvotes: 3