serializers.pyfrom django.db import models from django.contrib.auth.models import Userclass Speaker(models.Model): user = models.oneToOneField(User) @property def user__username(self): return self.user.username def __unipre__(self): return self.user.username
view.pyfrom .models import Speakerfrom rest_framework import serializersfrom django.contrib.auth.models import Userclass UserSerializer(serializers.HyperlinkedModelSerializer): class meta: model = User fields = ('url', 'username', 'email', 'groups') lookup_field = 'username'class SpeakerSerializer(serializers.HyperlinkedModelSerializer): user = serializers.HyperlinkedRelatedField( view_name='user-detail', read_only=True, lookup_field='username' ) class meta: model = Speaker fields = ('url', 'user') lookup_field = 'user__username'
from .models import Speakerfrom .serializers import SpeakerSerializer, UserSerializerfrom rest_framework import viewsetsfrom django.contrib.auth.models import Userclass UserViewSet(viewsets.ModelViewSet): queryset = User.objects.all() serializer_class = UserSerializer lookup_field = 'username'class SpeakerViewSet(viewsets.ModelViewSet): queryset = Speaker.objects.all().select_related('user') serializer_class = SpeakerSerializer lookup_field = 'user__username'
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)