gpt4 book ai didi

django - 带有 Django 休息框架的 manyToMany

转载 作者:行者123 更新时间:2023-12-04 18:32:51 24 4
gpt4 key购买 nike

我目前正在使用 django-rest-framework 提供的默认 CRUD 操作。它适用于普通模型,但我的一个模型与另一个标签模型具有多对多关系。这是模型的代码

class ActivityType(models.Model):
title = models.CharField(max_length=200)
slug = models.CharField(max_length=250,unique=True)

def __unicode__(self):
return self.slug

class Activity(models.Model):
owner = models.ForeignKey('auth.user')
title = models.CharField(max_length=200)
slug = models.CharField(max_length=250,unique=True)
description = models.TextField()
tags = models.ManyToManyField(ActivityType)
created = models.DateTimeField(auto_now_add=True, blank=True)

def __unicode__(self):
return self.slug

我想知道的是,如果可能的话,无需从头开始编写所有 CRUD 操作,将 DRF 与其集成的最佳方法是什么。

最佳答案

在你的 serializers.py

from rest_framework import serializers
from rest_framework import generics

from models import Activity
from models import ActivityType

class ActivityTypeSerializer(serializers.ModelSerializer):

class Meta:
model = ActivityType
fields = ('id', 'title', 'slug')

class ActivitySerializer(serializers.ModelSerializer):

tags = ActivityTypeSerializer(many=True, read_only=True)

class Meta:
model = Activity
fields = ('id', 'owner', 'title', 'slug', 'description', 'tags', 'created')

在你的 views.py 中
from rest_framework import viewsets

from serializers import ActivitySerializer
from serializers import ActivityTypeSerializer

from models import Activity
from models import ActivityType

class ActivityViewSet(viewsets.ModelViewSet):
queryset = Activity.objects.all()
serializer_class = ActivitySerializer

class ActivityTypeViewSet(viewsets.ModelViewSet):
queryset = ActivityType.objects.all()
serializer_class = ActivityTypeSerializer

并在你的 urls.py
from rest_framework.urlpatterns import format_suffix_patterns
from rest_framework import routers, serializers, viewsets
from rest_framework import generics
from rest_framework import viewsets, routers

from your_app.views import ActivityTypeViewSet
from your_app.views import ActivityViewSet

router = routers.DefaultRouter()

router.register(r'activitytypes', ActivityTypeViewSet)
router.register(r'activities', ActivityViewSet)

还要确保按照文档中的描述包含了 restframework url
 urlpatterns = patterns('',

# your other urls

url(r'^api/$', include('rest_framework.urls', namespace='rest_framework')),
url(r'api/accounts/', include('rest_framework.urls', namespace='rest_framework')),

)

关于django - 带有 Django 休息框架的 manyToMany,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37828358/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com