django rest框架通过OneToOneField的lookup_field

django rest框架通过OneToOneField的lookup_field,第1张

django rest框架通过OneToOneField的lookup_field

这就是我设法破解它的方式

models.py
from 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
serializers.py
from .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'
view.py
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'


欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/zaji/5647945.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-12-16
下一篇 2022-12-16

发表评论

登录后才能评论

评论列表(0条)

保存