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.
If you add a ForeignKey
, you actually have constructed two attributes:
fieldname
that is a reference to the related instance; andfieldname_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()
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With