如何将子模型过滤为另一个子模型?

时间:2019-08-30 16:42:19

标签: django django-models

我即将在Django中创建一个非常“干净”的模型。

  • PersonEntity的子级。并添加了字段user
  • ProfessionActivity的子项,具有自定义管理器,可以过滤类型为Activity(硬编码'profession')的type

您可以执行以下操作:

Entity.objects.filter(activities__activity_type__name='profession')

有效。但是我们可以做 cleaner

Person.objects.filter(activities__activity_type__name='profession',
                      activities__name="the job")

有效。我想做的是:

Person.objects.filter(professions__name="the job")

当我这样做时,我得到:

FieldError: Cannot resolve keyword 'professions' into field.
      Choices are: activities, entity_ptr, entity_ptr_id, id, is_physical, user, user_id

有没有办法做到这一点?

我无法查询所有具有特定entities

个人(不是Profession )的人
class Entity(BaseModel):
    is_physical = models.BooleanField(default=True)
    activities = models.ManyToManyField(Activity,
                                        related_name='entities')

class PersonManager(models.Manager):
    def get_queryset(self):
        return super().get_queryset().filter(is_physical=True)

class Person(Entity):
    objects = PersonManager()
    user = models.OneToOneField(User, blank=False, null=False,
                                on_delete=models.CASCADE)

对于Profession模型

class Activity(BaseModel):
    name = models.CharField(max_length=200, blank=True, null=True)
    activity_type = models.ForeignKey(ActivityType, on_delete=models.CASCADE,
                                      blank=True, null=True)

class ProfessionManager(models.Manager):
    @cached_property
    def activity_type_profession(self):
        try:
            return ActivityType.objects.get(name__iexact='profession')
        except ActivityType.DoesNotExist:
            return None

    def get_queryset(self):
        return super().get_queryset().filter(
            activity_type=self.activity_type_profession)

class Profession(Activity):
    objects = ProfessionManager()

0 个答案:

没有答案