[Answered ]-Change the foreignKey id to another Field

1👍

You can use the to_field=… parameter [Django-doc] to specify to what the ForeignKey should point. This should always be a unique field in the targetting model. So you can use:

class Classification(models.Model):
    person = models.ForeignKey(Person, to_field='name', on_delete=models.CASCADE)
    room = models.ForeignKey(Room, on_delete=models.CASCADE)
    date = models.DateField()
    create_date = models.DateTimeField(auto_now_add=True)

    def __str__(self):
       return f'({self.person_id} Take {self.room}  at {self.date})'

You should likely however recreate the migrations for the Classification model, and thus let this create a ForeignKey that references the name of the Person model.

You can here use self.person_id to avoid making an extra query to load the Person object. This will thus improve the efficiency when calling the __str__ method of a Classification object.

0👍

First you need to make the name a Pk in the Model primary_key=True
then in the ForeignKey set the to_field='name'

very easy …

👤Ayman

Leave a comment