该项目有两个应用程序,“ GreenApp”和“ BlueApp”,它们都具有与用户具有OneToOne关系的客户端模型。
from users.models import User
class Client(models.Model):
user = models.OneToOneField(User, related_name="green_client")
...
from rest_framework import serializers
from green_app.models.profiles import Client
class GreenClientSerializer(serializers.HyperlinkedModelSerializer)
class Meta:
model = Client
fields = ('url, 'user', ...)
from rest_framework import viewsets
from green_app.models.profiles import Client
class GreenClientViewset(viewsets.ModelViewSet):
queryset = Client.objects.all()
serializer_class = GreenClientSerializer
from users.models import User
class Client(models.Model):
user = models.OneToOneField(User, related_name="blue_client")
...
from rest_framework import serializers
from green_app.models.profiles import Client
class BlueClientSerializer(serializers.HyperlinkedModelSerializer)
class Meta:
model = Client
fields = ('url, 'user', ...)
from rest_framework import viewsets
from blue_app.models.profiles import Client
class BlueClientViewset(viewsets.ModelViewSet):
queryset = Client.objects.all()
serializer_class = BlueClientSerializer
from rest_framework import serializers
from green_app.serializers.profiles import GreenClientSerializer
from blue_app.serializers.profiles import BlueClientSerializer
from users.models import User
class UserSerializer(serializers.HyperlinkedModelSerializer):
class Meta:
model = User
fields = ('url', 'green_client', 'blue_client')
from rest_framework import viewsets, permissions
from users.models import User
class UserViewSet(viewsets.ModelViewSet):
queryset = User.objects.all()
serializer_class = UserSerializer
from django.urls import path, include
from rest_framework import routers
from users.viewsets import UserViewSet
from green_app.viewsets.profiles import GreenClientViewSet
from blue_app.viewsets.profiles import BlueClientViewSet
router = routers.DefaultRouter()
router.register(r'users', UserViewSet)
router.register(r'green/client', GreenClientViewSet)
router.register(r'blue/client', BlueClientViewSet)
url_patterns = [path('api/v0/', include(router.urls)),]
{
"url": "http://localhost:8000/auth/users/2/",
"green_client": "http://localhost:8000/api/v0/green/client/1/",
"blue_client": "http://localhost:8000/api/v0/blue/client/1/"
}
{
"url": "http://localhost:8000/auth/users/2/",
"green_client": "http://localhost:8000/api/v0/blue/client/1/",
"blue_client": "http://localhost:8000/api/v0/blue/client/1/"
}
请注意,两条路由都使用了蓝色路由
我在寻找this article时寻求帮助,因此我尝试将 base_name 添加到路由器中,如下所示:
router.register(r'green/client', GreenClientViewSet, 'blue-client')
router.register(r'blue/client', BlueClientViewSet, 'green-client')
这出现了一个新错误:
ImproperlyConfigured at /auth/users/2/
Could not resolve URL for hyperlinked relationship using view name "client-detail". You may have failed to include the related model in your API, or incorrectly configured the `lookup_field` attribute on this field.
在开始查看视图集之前,我想看看是否有任何方法可以快速解决此问题。