在Django中,模型类中定义的选择是否可以在模型类之外的其他地方访问?

时间:2018-02-17 23:40:54

标签: python django

我有以下模型类

class Movies(models.Model):
    MOVIE_CHOICES = (
            ('SHAW', 'Shashank Redemption'),
            ('NIGHT', 'In the Heat of the Night'),
            ('GOD', 'The God Father'),
            ('INVIC', 'Invictus'),
            )  
    title = models.CharField(max_length = 100, choices = MOVIE_CHOICES)

我正在将值写入数据库表。

当我查询数据库表时,我会收回密钥,例如我回来了INVIC

在我的代码中,我需要获取密钥的值,在本例中为Invictus。为了能够这样做,我需要访问包含键值对的数据结构。

如何通过模型类之外的键访问MOVIE_CHOICES?或者,我可以使用字典来设置选择值吗?

2 个答案:

答案 0 :(得分:3)

您可以使用实例方法get_{}_display

获取人类可读的选择名称

模型示例

movie = Movie.objects.get(pk=1)
movie.get_title_display()

答案 1 :(得分:2)

Django model field reference

中描述了一种很好的技术

示例:

from django import models

class Movies(models.Model):
    MOVIE_SHAWSHANK = 'shaw'
    MOVIE_NIGHT = 'night'
    MOVIE_GODFATHER = 'god'
    MOVIE_INVIC = 'invic'

    MOVIE_CHOICES = (
        (MOVIE_SHAWSHANK, 'The Shawshank Redemption'),
        (MOVIE_NIGHT, 'In the Heat of the Night'),
        (MOVIE_GODFATHER', 'The God Father'),
        (MOVIE_INVIC', 'Invictus'),
    )  

    title = models.CharField(max_length=100, choices=MOVIE_CHOICES)

现在,您可以执行以下操作以获得Shawshank Redemption'电影实例:

Movies.objects.filter(title=Movies.MOVIE_SHAWSHANK)

另一种技术是使用Enum(如果您使用的是Python 2.7,则必须安装它:Enum34

示例:

from django import models
from enum import Enum

class Movies(models.Model):

    class MOVIE_CHOICES(Enum):
        shawshank = ('shaw', 'The Shawshank Redemption')
        night = ('night', 'In the Heat of the Night')
        godfather = ('god', 'The God Father')
        invic = ('invic', 'Invictus')

        @classmethod
        def get_value(cls, member):
            return cls[member].value[0]

    title = models.CharField(
        max_length=100,
        choices=[x.value for x in MOVIE_CHOICES]
    )

现在,您可以执行以下操作以获得Shawshank Redemption'电影实例:

shawshank = Movies.MOVIE_CHOICES.get_value('shawshank')
Movies.objects.filter(flavor=shawshank)