父母可以有多个孩子类型时,如何获取相关的孩子类型?

时间:2019-05-19 14:08:06

标签: django django-models

假设我有3个这样的模型:

class Parent(models.model):
    CHILD_CHOICES = (
        ('ChildA', 'Child A'),
        ('ChildB', 'Child B'),
    )
    name = models.CharField(max_length=50)
    child_type = models.CharField(choices=CHILD_CHOICES, max_length=25, blank=True)

class ChildA(models.model):
    parent = OneToOneField('Parent',related_name='child_a',blank=True, null=True)

class ChildB(models.model):
    parent = OneToOneField('Parent',related_name='child_b',blank=True, null=True)

创建父级时,将创建关联的子模型(取决于child_type字段)。

如何在“父级”视图中从“父级”检索相应的“子级”类型,以便将自定义表单映射到合适的子级? (用于在同一视图中编辑“父代类型”和正确的“子代类型”

(在我的实际情况下,我有10种不同的孩子类型)

1 个答案:

答案 0 :(得分:1)

想到两个选择。

1)您可以使用可能更清洁的get_model()方法来找到正确的孩子。

2)您可以在查询集的中间执行IF语句。我已经对示例进行了硬编码,但是您可能可以一直拉出child_type变量,并使用注释。我真的只是在展示一个示例,说明如何使用多个相关模型分解和调整查询。

示例1:

from django.db.models import get_model

class ParentForm(forms.Form):   # or view
    ***code here**

    parent_model = Parent.objects.get(pk=1)

    # Get model name from CHILD_CHOICES.
    child_relation = [k for k, v in Parent.CHILD_CHOICES if v == parent_model.child_type]

    child_model = get_model('app_name', child_relation)
    child_model.objects.all()

    ***more code here***

示例2 :(有时根据您的设置方便):

class ParentManager(models.Manager):
    def get_child_info(self, child_type):
        try:
            query = super(ParentManager, self).get_queryset()

            # This line only works if the models have the same fields, otherwise do the below.
            query = query.values('id', 'name')

            if child_type == 'Child A':
                # Do this if your child models have different fields.
                query = query.values('id', 'name', 'unique_childA_field')
                query = query.select_related('child_a').all()
            elif child_type == 'Child B':
                # Do this if your child models have different fields.
                query = query.values('id', 'name', 'unique_childB_field')
                query = query.select_related('child_b').all()
        except Exception:
            query = None

    return query

class Parent(models.model):
    CHILD_CHOICES = (
        ('ChildA', 'Child A'),
        ('ChildB', 'Child B'),
    )
    name = models.CharField(max_lenght=50)
    child_type = models.CharField(choices=CHILD_CHOICES, max_length=25, blank=True)

    objects = ParentManager()

然后在您的视图或表单中

class ParentForm(forms.Form):   # or view
    ***code here**

    child_info = Parent.objects.get_child_info('Child A')

    ***more code here***