考虑以下模型:
class Book(models.Model):
id = models.AutoField(primary_key=True)
title = models.CharField(max_length=255)
publisher = models.ForeignKey('Publisher')
class Publisher(models.Model):
id = models.AutoField(primary_key=True)
publisher_name = models.CharField(max_length=255)
我想致电Book.objects.filter(id=123)
,但此输出应为:
{ 'id':123, 'title':'ABC', 'publisher':1 }
,
{ 'id': 123, 'title':'ABC', 'publisher':'XYZ Books' }
。
我的问题是,这可以通过select_related()
或仅更改models.ForeignKey()
参数来完成吗?
答案 0 :(得分:0)
如果普通用户另外只调用发布商,则可以使用Book.objects.filter(id=123).publisher_name
从图书对象中获取发布商名称。
class Book(models.Model):
id = models.AutoField(primary_key=True)
title = models.CharField(max_length=255)
publisher = models.ForeignKey('Publisher')
@property
def publisher_name(self):
return self.publisher.publisher_name
class Publisher(models.Model):
id = models.AutoField(primary_key=True)
publisher_name = models.CharField(max_length=255)