[Answered ]-How to use Primary Key as a foreignkey in Django

2👍

If you’re defining a foreign key on both sides of the relationship you either need a ManyToManyField or possibly a OneToOneField.

So just delete both foreign keys and define a many to many or one to one on one side of the relationship..

class RoomInfo(models.Model):
    hall = models.OneToOneField(Hallinfo)
👤Sayse

0👍

To do this, you can use string references [1]

class RoomInfo(models.Model):
    hall = models.ForeignKey("Hallinfo", unique=True)
    mobile_no = models.CharField(max_length=10, blank=True)

class HallInfo(models.Model):
    room = models.ForeignKey("RoomInfo", unique=True)
    mobile_no = models.CharField(max_length=10, blank=True)

But also you need to add null=True at least in one ForeignKey field, or you won’t be able to save first instance of a model without required reference value.

0👍

Try using another way to declare FK.
https://docs.djangoproject.com/en/1.9/ref/models/fields/#foreignkey

Personnaly I always use this notation:

manufacturer = models.ForeignKey(
    'app_name.ModelName',
    ....
)

In your case:

> class RoomInfo(models.Model):
>     hall = models.ForeignKey('appname.Hallinfo', unique=True)
>     mobile_no = models.CharField(max_length=10, blank=True)
> 
> class HallInfo(models.Model):
>     room = models.ForeignKey('appname.RoomInfo', unique=True)
>     mobile_no = models.CharField(max_length=10, blank=True)

Leave a comment