【问题标题】:Django: Is it possible to limit ContentType by base Parent?Django:是否可以通过基本父级限制 ContentType?
【发布时间】: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


    【解决方案1】:

    limit_choices_to 也接受可调用对象,所以是的,动态值应该是可能的:

    可以使用字典、Q 对象或返回字典或 Q 对象的可调用对象。

    所以按照这些思路应该可以工作:

    def get_children():
       return {'model__in': [c.__name__ for c in Parent.__subclasses__()]}
    

    然后……

    limit_choices_to=get_children
    

    甚至在一行中:

    limit_choices_to={'model__in': [c.__name__ for c in Parent.__subclasses__()]}
    

    【讨论】:

    • 谢谢你,你的回答是帮助,我修改它并使用它,我将列表转换为元组(不是必需的)并将 "name__in" 替换为 "model__in" 。
    猜你喜欢
    • 1970-01-01
    • 2018-06-08
    • 1970-01-01
    • 2013-03-13
    • 2016-06-20
    • 1970-01-01
    • 1970-01-01
    • 2019-07-31
    • 2022-12-03
    相关资源
    最近更新 更多