Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to read the primary key of a ForeignKey without loading the corresponding item?

Tags:

django

models

I have 2 Django models :

class A(models.Model):
    uniq_name = models.CharField(max_length=30,primary_key=True)
    info1 = models.CharField(max_length=30)     
    info2 = models.CharField(max_length=30)

class B(models.Model):
    a = models.ForeignKey(A)
    info3 = models.CharField(max_length=30)     
    info4 = models.CharField(max_length=30)

If I do :

b = B.objects.get(id = n), it generates one database request.

If I do

print b.a.pk : it generate another request.

Is that possible to access b.a primary key (I only need this information, not info1 nor info2) without generating another request nor using 'select_related()' ?

I could do a :

print b.__dict__['a_id']

It works, but it seems to me very ugly : do you have a nicer way ?

like image 793
Eric Avatar asked Aug 22 '11 09:08

Eric


1 Answers

You don't need to go via the dict: b.a_id works fine.

like image 129
Daniel Roseman Avatar answered Sep 29 '22 14:09

Daniel Roseman