开发者

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

I have 2 Django models :

class A(models.Model):
    uniq_name = models.CharField(max_length=30,primary_key=True)
    inf开发者_C百科o1 = 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 ?


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


No. That's how it's done.


If you want to do this dynamically (like I did):

related_field = 'a'
related_id = getattr(obj, f'{related_field}_{A._meta.pk.name}')
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜