【问题标题】:Django models using conditionsDjango 模型使用条件
【发布时间】:2016-03-26 17:19:51
【问题描述】:

我的 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_name”的字段用于课堂练习,但方式如下:

  • 对于 exercise_type=1,它应该是“最佳拉伸”
  • 对于 exercise_type=1,它应该是 'Butterfly reverse' 等等。

我怎样才能做到这一点?或者如果不是这样,有没有更好的方法来做到这一点?

底线:我的练习应该包含以下字段 - 类型、名称、描述、视频网址

【问题讨论】:

    标签: python django django-models django-rest-framework


    【解决方案1】:

    如果您想获得基于exercise_type 的字符串表示,只需使用get_exercise_type_display()。它将基于EXERCISE_TYPE_CHOICES 返回。

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

    【讨论】:

    • 你的意思是该字段如下所示:#Field for storage the exercise name exercise_name=(default=here go this logic)
    • @Nitish,我的意思是,您不需要定义/声明任何其他字段。相反,请使用 Django 提供的get_FOO_display。如果为该字段设置了choices,则由 Django 定义。
    • 我认为它是一个字段,因为我想将此值传播到客户端。现在我的序列化程序没有字段 exercise_name,因此它不会返回它。对吗?
    • @Nitish,您可以使用SerializerMethodField,无需修改模型类。
    猜你喜欢
    • 2021-08-05
    • 2017-01-24
    • 1970-01-01
    • 1970-01-01
    • 2015-06-10
    • 2016-12-26
    • 2020-11-01
    • 2018-04-12
    • 1970-01-01
    相关资源
    最近更新 更多