[英]Django Rest Framework - Edit related object set
I have a listing system in my Django project, with a Tag
object that attaches a list of Tag
s to a Listing
.我的 Django 项目中有一个列表系统,带有一个Tag
对象,该对象将Tag
列表附加到Listing
。 Each object has its own standard Viewset
which is passed to router.register()
.每个对象都有自己的标准Viewset
,它被传递给router.register()
。 The current way I'm editing or creating Tags is through a POST
or PATCH
to /tags/
.我目前编辑或创建标签的方式是通过POST
或PATCH
到/tags/
。 Ideally, I'd do this by doing a PATCH /listings/[id]/
with a JSON body of {"tags": [{"type": "foo", "text": "bar"}]}
.理想情况下,我会通过使用{"tags": [{"type": "foo", "text": "bar"}]}
的 JSON 主体执行PATCH /listings/[id]/
来做到这一点。 I've provided a slightly simplified version of my code below.我在下面提供了一个稍微简化的代码版本。
class NestedTagSerializer(serializers.ModelSerializer):
class Meta:
model = Tag
fields = ['text', 'type']
class ListingSerializer(serializers.ModelSerializer):
tags = NestedTagSerializer(many=True, read_only=False)
class Meta:
model = Listing
fields = ['tags', 'title', 'id']
class Listing(models.Model):
title = models.CharField(max_length=255)
description = models.TextField()
class Tag(models.Model):
listing = models.ForeignKey(Listing, on_delete=CASCADE)
text = models.CharField(max_length=255)
type = models.CharField(max_length=255)
Is there a nice way to do this with Django Rest Framework?使用 Django Rest Framework 有没有一种很好的方法可以做到这一点?
I faced similar issue before and for me routing was main issue.我之前遇到过类似的问题,对我来说路由是主要问题。
To implement nested routing, can use drf-extensions实现嵌套路由,可以使用drf-extensions
urls.py网址.py
from rest_framework import routers
from rest_framework_extensions.routers import NestedRouterMixin
class NestedDefaultRouter(NestedRouterMixin, routers.DefaultRouter):
pass
router = NestedDefaultRouter()
listing_router = router.register('listings/', ListingView)
tag_router = listing_router.register('tags', TagView, basename='tags', parents_query_lookups=['listing_id']
urlpartterns = router.urls
It will generate urls as following :它将生成如下网址:
/listings/ ListingView listing-list
/listings/<parent_lookup_listing_id>/tags/ TagView listing-tags-list
/listings/<parent_lookup_listing_id>/tags/<pk>/ TagView listing-tags-detail
/listings/<parent_lookup_listing_id>/tags/<pk>\.<format>/ TagView listing-tags-detail
/listings/<parent_lookup_listing_id>/tags\.<format>/ TagView listing-tags-list
parent_lookup_listing_id will be used to determine listing parent_lookup_listing_id将用于确定列表
listing_id = self.kwargs.get('parent_lookup_listing_id')
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.