1

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 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

5 Comments

I used value() because i want only the phone_number field.
@namjoo.org: in that case you can work with .only() (docs.djangoproject.com/en/dev/ref/models/querysets/#only) to boost performance, but you should not erode the model layer, especially since it then works with scalar values (or dictionaries), and thus all Django's meta logic no longer is in place.
I want to use student object not tell for query.
@namjoo.org: the last two code samples query the student model, for the first one we piggyback on the query to fetch all the related tell data with the same query.
@namjoo.org: and for the last one with the .values_list(...) we even simply retrieve the phone_number of the related tell model, but usually it is not a good idea to make use of .values(): django-antipatterns.com/antipattern/over-use-of-values.html

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.