这是我的班级:
class UserProfile(TimeStampedModel):
# some fields
class UserCohort(TimeStampedModel):
CHOICE1, CHOICE2, CHOICE3 = range(3)
COHORT_TYPES = (
(CHOICE1, 'Readable 1'),
(CHOICE2, 'Readable 2'),
(CHOICE3, 'Readable 3'))
user_profile = models.ForeignKey('UserProfile', related_name='cohorts')
cohort = models.IntegerField(choices=COHORT_TYPES)
我想通过可读名称而不是整数来进行过滤查询。如果我使用my_values = UserProfile.objects.filter(cohorts__cohort='Readable 1')
它不起作用,但如果我将'Readable 1'
替换为其对应的整数0
,则它可以正常工作。
有没有办法通过可读名称进行查询?
答案 0 :(得分:1)
没有办法使用Readable 1
值,因为这不是数据库中保存的值。但是,您可以使用您定义的常量CHOICE1
。
UserProfile.objects.filter(cohorts__cohort=UserCohort.CHOICE1)
答案 1 :(得分:0)
如果您从用户那里收到"Readable 1"
,那么您做错了。使用字段值作为输入元素的value
s。或者更好的是,使用ModelForm
来处理一切。