choices的用法

models中:

class Teacher(models.Model):
    """讲师、导师表"""

    name = models.CharField(max_length=32)
    role_choices = ((0, '讲师'), (1, '导师'))
    role = models.SmallIntegerField(choices=role_choices, default=0)

 

views中:

class Teacher(APIView):
    def get(self,request):

        obj = models.Teacher.objects.filter(pk=1)
        obj1 = Teacher_Seri(obj,many=True)

        return Response(obj1.data)

 

自定义序列化:

class Teacher_Seri(serializers.ModelSerializer):
    class Meta:
        model = models.Teacher
        fields = "__all__"
  # 根据source 的特性
    role = serializers.CharField(source="get_role_display")

 

注意:

models中:

class Person(models.Model):
    G=(('chen','jian'),('hong','yi'),('rt','ju'))
    gender=models.CharField(max_length=20,choices=G)

第一个参数是值,将被存储到数据库里。第二个值是在admin中下拉列表的显示。

应用:

p = Person.objects.get(gender='chen')
a = p.get_gender_display()
print(a)     # jian

p = Person(gender="rt")
b = p.get_gender_display()
print(b)    # ju

当我们插入一条choices中不存在的记录时也是可以成功的。比如:

p = Person(gender="yiadf")
a = p.get_gender_display()

print(a)  #   yiadf

 

posted @ 2019-03-05 22:40  萤huo虫  阅读(842)  评论(0编辑  收藏  举报