简体   繁体   中英

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 . Each object has its own standard Viewset which is passed to router.register() . The current way I'm editing or creating Tags is through a POST or PATCH to /tags/ . Ideally, I'd do this by doing a PATCH /listings/[id]/ with a JSON body of {"tags": [{"type": "foo", "text": "bar"}]} . I've provided a slightly simplified version of my code below.

serializers.py

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']

models.py

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?

I faced similar issue before and for me routing was main issue.

To implement nested routing, can use drf-extensions

urls.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

listing_id = self.kwargs.get('parent_lookup_listing_id')

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM