How to get value of ForeignKey in views.py?

Viewed 39

I have below models.py and views.py in Django(This is only a example). How can i print the value of ForeignKey in views.py?

models.py

class student(models.Model):
    name = models.CharField(max_length=50)
    desc = models.CharField(max_length=100, blank=True, null=True)
    phone_number = models.ForeignKey(tell,on_delete=models.SET_NULL, null = True,blank=True)

    def __str__(self):
         return self.name

class tell(models.Model):
    phone_number = models.CharField(max_length=20, blank=True, null=True)

    def __str__(self):
         return self.phone_number

views.py

phones =  student.objects.values('phone_number')
phone =   list(phones)
for ob in phone:
   print(ob)

This prints only id but i want the value of foreign key.

1 Answers

This is one of the (many) reasons not to use .values(…) [Django-doc]: it erodes the model logical layer of a Django model.

You can work with:

tell.objects.filter(student__isnull=False)

this will retrieve all tell ojects that have at least a related Student.

You can also use .select_related(…) [Django-doc] to select the telephone number while retrieving the students, and thus avoid an N+1 problem:

students = student.objects.select_related('phone_number'):
for stud in students:
    print(stud.phone_number)

If you really want to work with the phone_number of the tell model, you can work with .values_list(…) [Django-doc], and work with:

phones = student.objects.values_list('phone_number__phone_number', flat=True)
for phone in phones:
    print(phone)

but this are thus not tell objects, and thus updating, refrehing, a record is not possible in that case.

Related