Django REST框架Serializer pk字段?

时间:2013-03-14 19:53:27

标签: django django-rest-framework

Django-REST-framework中Serializer类的pk字段是什么?

我认为它是主键,但名称'pk'是保留的术语吗? Serializer类如何知道它是Snippet模型的主键?

我在Snippet模型中看不到名为'pk'的字段。

class SnippetSerializer(serializers.Serializer):
    pk = serializers.Field()  # Note: `Field` is an untyped read-only field.
    title = serializers.CharField(required=False,
                                  max_length=100)
    code = serializers.CharField(widget=widgets.Textarea,
                                 max_length=100000)
    linenos = serializers.BooleanField(required=False)
    language = serializers.ChoiceField(choices=LANGUAGE_CHOICES,
                                       default='python')
    style = serializers.ChoiceField(choices=STYLE_CHOICES,
                                    default='friendly')

....类SnippetSeralizer继续

class Snippet(models.Model):
    created = models.DateTimeField(auto_now_add=True)
    title = models.CharField(max_length=100, blank=True, default='')
    code = models.TextField()
    linenos = models.BooleanField(default=False)
    language = models.CharField(choices=LANGUAGE_CHOICES,
                                default='python',
                                max_length=100)
    style = models.CharField(choices=STYLE_CHOICES,
                             default='friendly',
                             max_length=100)

    class Meta:
        ordering = ('created',)

2 个答案:

答案 0 :(得分:10)

pk是一个位于Model基础django.db.models类的属性:

class Model(object):
    ...
    pk = property(_get_pk_val, _set_pk_val)
    ...

用于标识模型的主键。我没有使用过Django-REST,但它们可能只是将它映射到模型上的字段。

答案 1 :(得分:1)

如果您在Django REST Framework中使用通用视图,并且想为pk字段使用其他名称,例如id,则可以在您的{查看lookup_field