我有以下模型,引用了一个对象和一个继承自的对象:
class Employee(models.Model):
user = models.OneToOneField(User, blank=True, null=True)
entity = models.ForeignKey('companies.Entity', blank=True, null=True)
brand = models.OneToOneField('companies.Brand', related_name='brand', blank=True, null=True)
class Entity(models.Model):
name = models.CharField('Name', max_length=255, db_index=True)
class Brand(Entity):
company_name = models.CharField(max_length=128, blank=True, null=True)
问题是当我尝试引用反向关系时,我无法访问Brand只有实体。我想让员工与品牌联系起来。我试过这个:
brands = Brand.objects.filter(pk=2)
for b in brands:
print b.employee_set.all().query
输出:
SELECT * FROM `employee` WHERE `employee`.`entity_id` = 2
我希望它输出:
SELECT * FROM `employee` WHERE `employee`.`brand_id` = 2
答案 0 :(得分:0)
在您的模型文件中,您定义实体和品牌的方式称为多表继承,django将自动在实体和品牌之间创建OneToOneField关系,但在您的员工模型中,实体是您的外键,但品牌与您的员工在onetoonefield模型,那不会起作用。您可以通过在实体上声明自己的OneToOneField并使用parent_link = True来覆盖该字段,因此实体和品牌之间没有oneToOneField关系,请查看详细信息:https://docs.djangoproject.com/en/1.11/topics/db/models/#multi-table-inheritance。希望这能帮助你。