【发布时间】:2017-03-16 15:14:53
【问题描述】:
我有一个抽象基类“Parent”,从中派生出两个子类“Child1”和“Child2”。每个孩子可以有一组“状态”。 我像这样使用“ContentType”、“GenericForeignKey”和“GenericRelation”:
from django.db import models
from django.contrib.contenttypes.generic import GenericRelation, GenericForeignKey
from django.contrib.contenttypes.models import ContentType
class Parent(models.Model):
name = models.CharField(max_length=30, blank=True)
class Meta:
abstract = True
def __str__(self):
return self.name
class Child1(Parent):
id_camp = models.PositiveIntegerField()
config_type = models.CharField(max_length=30)
status_set = GenericRelation(Status)
class Child2(Parent):
temperature = models.FloatField(null=True, blank=True)
status_set = GenericRelation(Status)
class Status(models.Model):
code = models.CharField(max_length=10, null=True, blank=True)
message = models.CharField(max_length=100, null=True, blank=True)
content_type = models.ForeignKey(ContentType, limit_choices_to={'name__in': ('child1', 'child2',)}, null=True, blank=True)
object_id = models.PositiveIntegerField()
content_object = GenericForeignKey('content_type', 'object_id')
实际的解决方案工作正常,但现在内容类型选择的限制是“名称”,最终我会在以后创建更多的父子类。我想用limit_choices_to children of parent 之类的东西替换limit_choices_to={'name__in': ('child1', 'child2',)} 有什么直接的方法吗?
【问题讨论】:
标签: django django-models orm relational-database