Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django: Get value of foreign key field without additional SQL to DB

Model

class Photo(models.Model):
    doc_pic = models.ImageField(upload_to='specialist/', default='', null=True, blank=True, max_length=250)
    doctor = models.ForeignKey(Doctor, blank=True, null=True, on_delete=models.SET_NULL, related_name='photos')

I query the photos

temp = Photo.objects.all()

Now I want the ID of doctor that is saved in doctor field (for first element)

print(temp[0].doctor)

and I receive the Doctor object. But I want the numeric ID. How can I get that?

I am aware that I can get it with

temp[0].doctor.id 

but this will submit another query to the DB that I want to avoid.

like image 270
caliph Avatar asked May 28 '18 12:05

caliph


1 Answers

If you add a ForeignKey, you actually have constructed two attributes:

  • fieldname that is a reference to the related instance; and
  • fieldname_id which is the real database column, and this stores a primary key of the table it refers to.

So you can write:

temp[0].doctor_id

In case you are only interested in the doctor_id, and not in other fields, you can make the query more efficient with values_list:

Photo.objects.values_list('doctor_id', flat=True).first()

In fact if you use values_list, you can use doctor here directly as field, and it will only return the identifier, not the corresponding Doctor instance:

# equivalent to values_list with doctor_id
Photo.objects.values_list('doctor', flat=True).first()
like image 135
Willem Van Onsem Avatar answered Sep 26 '22 22:09

Willem Van Onsem