Django REST框架的嵌套API视图?
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Django REST框架的嵌套API视图?相关的知识,希望对你有一定的参考价值。
目前我开发了以下代码,让我获得每个用户的联系人列表。视图返回用户的联系人的ID号。我需要获取所述联系人的“名称”和“last_name”属性,而不是ID号。我是Django的REST框架的新手,我不太确定下一步该做什么,但我相信我必须嵌套APIView。我真的很感激一些帮助!
views.朋友
def list_contacts(request, id_profile):
url = request.build_absolute_uri(reverse('api_users:contact_list', kwargs={'pk':id_profile}))
response = requests.get(url)
profile = Profile.objects.get(pk=id_profile)
if response.status_code == status.HTTP_200_OK:
data = response.content
user = json.loads(data)
return render(request, 'profiles/contact_list.html', {'user':user})
models.朋友
class Profile(models.Model):
id_user = models.OneToOneField(User, on_delete=models.CASCADE)
name = models.CharField(max_length=50)
last_name = models.CharField(max_length=50)
birthday = models.DateField(auto_now=False)
description = models.CharField(max_length=100)
profile_picture = models.ImageField(upload_to='images/profiles/%Y/%m/%d', blank=False)
active = models.BooleanField(default = False)
contacts = models.ManyToManyField('self', blank=True, default='null')
created_at = models.DateTimeField(default=timezone.now)
updated_at = models.DateTimeField(default=timezone.now)
deleted_at = models.DateTimeField(blank=True, null=True)
class Meta:
ordering = ('-id',)
def __str__(self):
return self.name+' '+self.last_name
def active_profiles():
return Profile.objects.filter(active=True)
API / views.py
class ContactListView(generics.ListAPIView):
queryset = Profile.objects.all()
serializer_class = UserContactListSerializer
filter_backends = (filters.SearchFilter,)
search_fields = ('name', 'last_name',)
def get(self, request, pk, format=None):
contacts = Profile.objects.get(pk=pk)
serializer = UserContactListSerializer(contacts)
return Response(serializer.data)
API / serializers.py
class UserContactListSerializer(serializers.ModelSerializer):
class Meta:
model = Profile
fields = ['name','last_name','contacts']
答案
我不知道你的list_contacts
到底发生了什么,但是如果你想要使用相同的序列化器作为一个字段本身,你目前不能。
虽然Django模型允许您使用'self'
作为参考,但DRF却没有。
你可以做的是创建另一个序列化程序并将其用作字段。
class UserSerializer(serializers.ModelSerializer):
class Meta:
model = Profile
fields = ("id", "first_name", "last_name")
class UserContactListSerializer(serializers.ModelSerializer):
contacts = UserSerializer(many=True)
class Meta:
model = Profile
fields = ("id", "first_name", "last_name", "contacts")
以上是关于Django REST框架的嵌套API视图?的主要内容,如果未能解决你的问题,请参考以下文章