PrimaryKeyRelatedField

models.py中
class Snippet(models.Model):
    owner = models.ForeignKey('auth.User', related_name="snippets", on_delete=models.CASCADE)

serializers.py当中
from django.contrib.auth.models import User

from snippets.models import Snippet
class UserSerializer(serializers.ModelSerializer):
    snippets = serializers.PrimaryKeyRelatedField(many=True, queryset=Snippet.objects.all())

    class Meta:
        model = User
        fields = ("id", "username", "snippets")
        
"""
因为'snippets' 在用户模型中是一个反向关联关系。
在使用 ModelSerializer 类时它默认不会被包含,
所以我们需要为它添加一个显式字段。
"""

你可能感兴趣的:(PrimaryKeyRelatedField)