Django多态和GenericRelation字段。如何获得所有过滤的对象?

时间:2019-06-14 08:59:51

标签: django django-models django-contenttypes django-polymorphic django-generic-relations

models.py

class File(models.Model):--> content_type_id=4
    is_recorded = models.BooleanField(verbose_name=_('is recorded'), default=False)
    content_type = models.ForeignKey(ContentType, on_delete=models.CASCADE, null=True, blank=True)
    object_id = models.PositiveIntegerField(null=True, blank=True)
    content_object = GenericForeignKey('content_type', 'object_id')


class Parent(PolymorphicModel): --> content_type_id=1
    files = GenericRelation(File)
    field0 = models.CharField(verbose_name=_('field0'), max_length=255, blank=True, null=True)

class Child1(Parent): --> content_type_id=2
    field1 = models.CharField(verbose_name=_('field1'), max_length=255, blank=True, null=True)

class Child2(Parent): --> content_type_id=3
    field2 = models.CharField(verbose_name=_('field2'), max_length=255, blank=True, null=True)

运行查询1

Parent.object.all()
[ <Child1:  id 1>,
  <Child2:  id 2>]

SQL 2

SELECT `parent`.`id`,    
   `parent`.`polymorphic_ctype_id`,
   `parent`.`content_type_id`,
   `parent`.`object_id`,
   `parent`.`fiedl0`,
FROM `events_event`

很好;


运行查询2

Child2.object.filter(files__is_recorded=True)
[<Child2:   id 1>]

SQL 2

SELECT DISTINCT `parent`.`id`,
            `parent`.`polymorphic_ctype_id`,
            `parent`.`content_type_id`,
            `parent`.`object_id`,
            `child2`.`parent_ptr_id`,
            `child2`.`field1`,
FROM `child2`
     INNER JOIN `parent` ON (`child2`.`parent_ptr_id` = `parent`.`id`)
     INNER JOIN `parent` T3
                ON (`child2`.`parent_ptr_id` = T3.`object_id` AND (T3.`content_type_id` = 2))
     INNER JOIN `file` ON (T3.`id` = `file`.`id`)

很好;


运行查询3

Parent.object.filter(files__is_recorded=True)
[]

SQL 3

SELECT DISTINCT `parent`.`id`,
            `parent`.`polymorphic_ctype_id`,
            `parent`.`content_type_id`,
            `parent`.`object_id`,
FROM `parent`
     INNER JOIN `file`
                ON (`parent`.`id` = `file`.`object_id` AND (`file`.`content_type_id` = 1))

不好。

我如何获取所有具有文件__is_recorded = True的子对象(Child1,Child2)(在文件模型中不添加另一个GenericForeignKey并链接到父模型)?

0 个答案:

没有答案