hey Guyzz i am new in django so can anybody help me out in this i want to add two foreign key in one class how can i do it?
CodePudding user response:
Please, try to read PEP8 (https://peps.python.org/pep-0008/)
You can add more ForeignKeys
to the same model, but you should add different related_name
for every FK:
class Fees(models.Model):
course=models.ForeignKey("app2.coursel", related_name='courses', on_delete=models.CASCADE)
branch=models.ForeignKey("app2.coursel", related_name='branches', on_delete=models.CASCADE)
fees=models.IntegerField()
And i am agree, this question war already answered here: Django model with 2 foreign keys from the same table
CodePudding user response:
Yes,
If you want two Foreign Keys pointing at two different models / table: do @maxim's
- Example: 1 to courses, 1 to fees
If you want two Foreign Keys pointing at the same model / table, you can do Many-to-Many: https://docs.djangoproject.com/en/4.1/topics/db/examples/many_to_many/
- Example: 2 courses
Many-To-Many is a little more complicated and finicky than normal Foreign Keys (imo) but it's pretty nice once you get used to it