我即将在Django中创建一个非常“干净”的模型。
Person
是Entity
的子级。并添加了字段user
。Profession
是Activity
的子项,具有自定义管理器,可以过滤类型为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()