<p>tl;博士:</p>
<p>对于一个简单得多的线性解,对于M2M,我使用了如下形式的解:</p>
<pre><code>serializer = ServiceSerializer(instance=inst, data={'name':'updated', 'countries': [1,3]}, partial=True)
if serializer.is_valid():
serializer.save()
</code></pre>
<p>更完整的示例包括:</p>
<p><strong>型号.py</strong></p>
<pre><code>from django.db import models
class Country(models.Model):
name = models.CharField(max_length=50, null=False, blank=False)
class Service(models.Model):
name = models.CharField(max_length=20, null=True)
countries = models.ManyToManyField('Country')
</code></pre>
<p><strong>序列化程序.py</strong></p>
<pre><code>from rest_framework import serializers
from .models import *
class CountrySerializer(serializers.ModelSerializer):
class Meta:
model = Country
fields = ('name',)
class ServiceSerializer(serializers.ModelSerializer):
class Meta:
model = Service
fields = ('name', 'countries',)
</code></pre>
<p>确保为测试创建了一些虚拟服务和国家/地区实例。然后您可以更新函数中的实例,如下所示:</p>
<p><strong>更新示例</strong></p>
<pre><code># get an object instance by key:
inst = ServiceOffering.objects.get(pk=1)
# Pass the object instance to the serializer and a dictionary
# Stating the fields and values to update. The key here is
# Passing an instance object and the 'partial' argument:
serializer = ServiceSerializer(instance=inst, data={'name':'updated', 'countries': [1,3]}, partial=True)
# validate the serializer and save
if serializer.is_valid():
serializer.save()
return 'Saved successfully!'
else:
print("serializer not valid")
print(serializer.errors)
print(serializer.data)
return "Save failed"
</code></pre>
<p>如果检查相关表,则会执行更新,包括M2M桥接表。</p>
<p>要扩展此示例,我们可以用非常类似的方式创建对象实例:</p>
<pre><code>### Create a new instance example:
# get the potential drop down options:
countries = ['Germany', 'France']
# get the primary keys of the objects:
countries = list(Country.objects.filter(name__in=countries).values_list('pk', flat=True))
# put in to a dictionary and serialize:
data = {'countries': countries, 'name': 'hello-world'}
serializer = ServiceOfferingSerializer(data=data)
</code></pre>