简体   繁体   中英

Can we Add Two foreign key in one class in django?

在此处输入图像描述

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?

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM