https://Gist.github.com/ranman/3d97ea9054c984bca75e
望ましい動作
ユーザールックアップはユーザー名で行われます:/api/users/randall
スピーカーの検索はユーザー名でも行われます:/api/speakers/randall
制約
すべてのユーザーがスピーカーであるとは限りません。スピーカーはすべてユーザーです。
models.py
from Django.contrib.auth.models import User
class Speaker(models.Model):
user = models.OneToOneField(User)
serializers.py
class 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
lookup_field = 'user'
views.py
class 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"
これが機能しないように、lookup_fieldタイプとserializerタイプのさまざまな呼び出しを試しました。たくさんのコードがなければそれは不可能かもしれません。どういう方向に行けるのか迷っています。
ありがとう!
これは私がどうにかハックした方法です
from Django.db import models
from Django.contrib.auth.models import User
class Speaker(models.Model):
user = models.OneToOneField(User)
@property
def user__username(self):
return self.user.username
def __unicode__(self):
return self.user.username
from .models import Speaker
from rest_framework import serializers
from Django.contrib.auth.models import User
class 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 Speaker
from .serializers import SpeakerSerializer, UserSerializer
from rest_framework import viewsets
from Django.contrib.auth.models import User
class 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'
このアプローチを試しましたか?
class SpeakerViewSet(viewsets.ModelViewSet):
queryset = Speaker.objects.all().select_related('user')
serializer_class = SpeakerSerializer
filter_backends = (filters.DjangoFilterBackend,)
filter_fields = ('user', 'user__username',)