Python 使用条件的Django模型

Python 使用条件的Django模型,python,django,django-models,django-rest-framework,Python,Django,Django Models,Django Rest Framework,My models.py如下所示: class Exercise(models.Model): #Field for storing exercise type EXERCISE_TYPE_CHOICES = ( (1, 'Best stretch'), (2, 'Butterfly reverse'), (3, 'Squat row'), (4, 'Plank'), (5, 'Push up'),

My models.py如下所示:

class Exercise(models.Model):

    #Field for storing exercise type
    EXERCISE_TYPE_CHOICES = (
        (1, 'Best stretch'),
        (2, 'Butterfly reverse'),
        (3, 'Squat row'),
        (4, 'Plank'),
        (5, 'Push up'),
        (6, 'Side plank'),
        (7, 'Squat'),
    )
    exercise_type = models.IntegerField(choices=EXERCISE_TYPE_CHOICES)

    #Field for storing exercise name
    -- Here comes the logic --

    #Field for storing intensity level
    INTENSITY_LEVEL_CHOICES = (
        (1, 'Really simple'),
        (2, 'Rather Simple'),
        (3, 'Simple'),
        (4, 'Okay'),
        (5, 'Difficult'),
        (6, 'Rather Difficult'),
        (7, 'Really Difficult'),
    )
    intensity_level = models.IntegerField(choices=INTENSITY_LEVEL_CHOICES)

    #Field for storing video url for a particular exercise
    video_url = models.URLField()

    #Field for storing description of the exercise
    description = models.CharField(max_length=500)
我想为课堂练习设置一个名为“exercise\u name”的字段,但方法如下:

  • 对于练习类型=1,应为“最佳伸展”
  • 对于练习_type=1,它应该是“蝶形反转”,以此类推
我怎样才能做到这一点?或者,如果不是这样,还有更好的方法吗


底线:我的练习应该有以下字段-类型、名称、描述、视频url

如果你想基于
练习类型
获得字符串表示,只需使用。它将根据
练习类型选择返回

ex = Exercise(exercise_type=1, intensity_level=1)
ex.get_exercise_type_display()    # => 'Best stretch'
ex.get_intensity_level_display()  # => 'Really simple'

您的意思是该字段将如下所示:#用于存储练习名的字段exercise_name=(默认值=这是逻辑)@Nitish,我的意思是,您不需要定义/声明任何其他字段。相反,使用Django提供的
get\u FOO\u display
。如果为字段设置了
choices
,它由Django定义。我认为它是一个字段,因为我想将此值传播到客户端。现在,我的序列化程序没有字段名,因此不会返回它。对吗?@Nitish,您可以在不修改模型计算的情况下使用。