python - Django Rest Framework 将对象附加到多对多字段而不删除前一个
问题描述
我是DRF的新手,无法弄清楚如何在不删除前一个的情况下将对象附加到多对多字段。
我正在使用PATCH更新字段 MONITORS 但是以前的值被实际值替换。我想附加它。
API GET
是:
{
"id": 1,
"created": "2018-05-02T23:43:07.605000Z",
"modified": "2021-04-03T10:25:12.280896Z",
"companies_house_id": "",
"name": "Ellison PLC",
"description": "",
"date_founded": "2018-04-28",
"country": 4,
"creator": 7,
"monitors": [
3
]
}
在PATCH {"monitors":[11]}
我得到:
{
"id": 1,
"created": "2018-05-02T23:43:07.605000Z",
"modified": "2021-04-03T10:25:12.280896Z",
"companies_house_id": "",
"name": "Ellison PLC",
"description": "",
"date_founded": "2018-04-28",
"country": 4,
"creator": 7,
"monitors": [
11
]
}
我希望最终的 GET API 是"monitors": [3, 11]
模型.py
class Company(TimeStampedModel):
companies_house_id = models.CharField(max_length=8, blank=True)
name = models.CharField(max_length=200, blank=True)
description = models.TextField(blank=True)
date_founded = models.DateField(null=True, blank=True)
country = models.ForeignKey(Country, on_delete=models.PROTECT, blank=True)
creator = models.ForeignKey(
settings.AUTH_USER_MODEL,
on_delete=models.SET_NULL,
null=True,
related_name='companies_created'
)
monitors = models.ManyToManyField(
settings.AUTH_USER_MODEL,
blank=True,
related_name='companies_monitored',
help_text='Users who want to be notified of updates to this company'
)
def __unicode__(self):
return u'{0}'.format(self.name)
序列化程序.py
from rest_framework import serializers
from .models import Company
from django.contrib.auth import get_user_model
class CompanySerializer(serializers.ModelSerializer):
class Meta:
model = Company
fields = '__all__'
class UserSerializer(serializers.ModelSerializer):
companies_monitored = CompanySerializer(many=True, read_only=True)
# companies_moniotred = serializers.PrimaryKeyRelatedField(many=True, read_only=True)
class Meta:
model = get_user_model()
fields = ('id', 'username', 'companies_monitored')
视图.py
class CompanyDetailsView(generics.RetrieveUpdateAPIView):
queryset = Company.objects.all()
serializer_class = CompanySerializer
class UserList(generics.ListCreateAPIView):
queryset = get_user_model().objects.all()
serializer_class = UserSerializer
class UserDetail(generics.RetrieveUpdateDestroyAPIView):
queryset = get_user_model().objects.all()
serializer_class = UserSerializer
def get_object(self, username):
username = get_object_or_404(get_user_model(), username=username)
return username
def get(self, request, username):
username = self.get_object(username)
serializer = UserSerializer(username)
return Response(serializer.data)
网址.py
from django.conf.urls import url
from django.urls import path
from . import views
from .views import CompanyDetailsView, UserList, UserDetail
urlpatterns = [
path('details/<int:pk>/', CompanyDetailsView.as_view(), name='company_details'),
path('users/<str:username>/', UserDetail.as_view(), name='profile_view'),
]
解决方案
对方法使用不同的序列化程序PATCH
。
class CompanyDetailsView(generics.RetrieveUpdateAPIView):
queryset = Company.objects.all()
serializer_class = CompanySerializer
def get_serializer_class(self):
if self.request.method == 'PATCH':
return CompanyPatchSerializer
return self.serializer_class
并在序列化程序中处理您需要的内容
class CompanyPatchSerializer(serializers.ModelSerializer):
class Meta:
model = Company
fields = '__all__'
@transaction.atomic
def update(self, instance, validated_data):
if 'monitors' in validated_data:
monitor_ids = validated_data.pop('monitors')
# todo: handle get_or_create
return super().update(instance, validated_data)
我不喜欢隐式 m2m 模型,所以我的建议也是添加through
模型。
推荐阅读
- javascript - 使用 jQuery 处理这些数据的正确方法是什么?
- javascript - Webpack 构建速度性能
- r - 用 Shiny Dashboard 包裹方程
- javafx - SetPadding 在有许多孩子的布局中的一个单一元素
- css - 开发人员有没有办法以与默认颜色不同的颜色突出显示网站上的浏览器 (f3) 搜索结果?
- python - 如何在 PyCharm 中运行时打开调试
- c# - File.Delete 上的 System.IO.DirectoryNotFoundException 获取有效路径
- javascript - Django 中的 Vue.js 初始化
- r - 如何使用 Rscript 和 readr 从 aws s3 获取数据
- c# - 如何“释放”实现 IDispose 的成员变量?