Django中的外键“自动列查找”

时间:2017-10-12 04:32:16

标签: python sql django

考虑以下模型:

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()参数来完成吗?

1 个答案:

答案 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)