Django Rest Framework-JSON发布请求ManyTomany字段问题

时间:2018-10-28 08:35:54

标签: python json django post django-rest-framework

TLDR;使用Django Rest框架,如何仅使用所述M2M字段的ID / PK对具有多对多关系字段的API资源进行POST(应用程序/ json内容)?

我目前正在为使用Django Rest Framework的大学项目建模应用程序。以下模型表示应用程序上的志愿者(为了避免污染代码,我隐藏了一些小细节)

class Volunteer(models.Model):

first_name = models.CharField(max_length=100)
last_name = models.CharField(max_length=100)
state = models.CharField(max_length=2, choices=STATE_CHOICES)
city = models.CharField(max_length=255)
gender = models.CharField(max_length=2, choices=GENDER_CHOICES, blank=True, null=True)
phone = models.CharField(max_length=13) 
email = models.EmailField(max_length=100)
description = models.TextField(max_length=500)  
photo = models.ImageField(null=True, blank=True)
created_at = models.DateTimeField(auto_now_add=True)
interest_areas = models.ManyToManyField(VolunteeringArea, blank=True)

class Meta:
    verbose_name_plural = "Volunteers"
    ordering = ("first_name", "last_name")

def __str__(self):
    return self.first_name + ' ' + self.last_name

def get_absolute_url(self):
    return reverse('volunteers:volunteer-detail', kwargs={'pk': self.id})

相应的序列化器如下所示:

class VolunteerSerializer(serializers.ModelSerializer):

    interest_areas = VolunteeringAreaSerializer(many=True)

    class Meta:
        model = Volunteer
        fields = ('id', 'first_name', 'last_name', 'phone', 'email', 'state', 'gender', 'interest_areas', 'city', 'description', 'photo')
        read_only_fields = ('created_at', )


    def to_representation(self, instance):
        representation = super(VolunteerSerializer, self).to_representation(instance)
        representation['interest_areas'] = VolunteeringAreaSerializer(instance.interest_areas.all(), many=True).data
        return representation 

您可能会注意到,每个志愿者可能都有许多感兴趣的领域(许多领域)。下面的模型表示它:

class VolunteeringArea(models.Model):

    title = models.CharField(max_length=100)
    description = models.TextField(max_length=512)
    created_at = models.DateTimeField(auto_now_add=True)
    is_active = models.BooleanField(default=False)

    class Meta:
        verbose_name_plural = "VolunteeringAreas"

    def __str__(self):
        return self.title

    def slug(self):
        return slugify(self.title

)    

相应的序列化器是:

class VolunteeringAreaSerializer(serializers.ModelSerializer):

    class Meta:

        model = VolunteeringArea
        fields = ('id', 'title', 'description')
        read_only_fields = ('created_at', 'is_active') 

我的问题是,当尝试通过提供感兴趣的区域ID的POST(application / json)创建一个新的Volunteer时,我得到一个响应,说我应该提供一个dict,但是应用程序却接收到一个int。我意识到该应用程序期望有一个来自dicted_area的所有字段的完整字典,但是我只想提供ID / PK,它将创建对象。

我一直在互联网上找了几个小时,看来我应该先创建没有interest_areas的对象,然后将它们添加到该对象中。我试图在模块的views.py上定义一个create方法(与框架定义的原始create方法相同),但是它似乎卡在serializer.is_valid()上,最有可能表明所提供的值在interested_area字段中无效。

def post(self, request, format=None):
    return self.create(request)


def create(self, request, *args, **kwargs):

    serializer = self.get_serializer(data=request.data)
    serializer.is_valid(raise_exception=True)
    self.perform_create(serializer)
    headers = self.get_success_headers(serializer.data)
    return Response(serializer.data, status=status.HTTP_201_CREATED, headers=headers)

def get_serializer(self, *args, **kwargs):

    serializer_class = self.get_serializer_class()
    kwargs['context'] = self.get_serializer_context()
    return serializer_class(*args, **kwargs)

我的错误是什么,我该如何做?

为了提供信息,这是使用邮递员的请求的正文内容:

{
    "interest_areas": [0,1],
    "first_name":"NameOfThePerson",
    "last_name":"LastNameOfThePerson",
    "phone":"RandomCellphoneNumber",
    "email":"randomemail@randomemail.com",
    "gender":"Gender",
    "state":"State",
    "city":"City",
    "description":"randomDescription"
}

谢谢您的帮助!

1 个答案:

答案 0 :(得分:2)

您收到此错误,因为您将VolunteeringAreaSerializer作为NestedSerialiser包含在内。要仅对您的VolunteeringArea使用ID,请使用PrimaryKeyRelatedField和bulk_create这样。

class VolunteerSerializer(serializers.ModelSerializer):

    interest_areas = serializers.PrimaryKeyRelatedField(many=True, 
                     queryset=models.VolunteeringArea.objects.all())


    class Meta:
        model = Volunteer
        fields = ('id', 'first_name', 'last_name', 'phone', 'email', 'state', 
              'gender', 'interest_areas', 'city', 'description', 'photo')

    def create(self, validated_data):
        areas = validated_data.pop('interest_areas', [])
        # create your volunteer here..
        #......
        ThroughModel = Volunteer.interest_areas.through
        # bulk-create through model instance fields
        ThroughModel.objects.bulk_create([
                ThroughModel(volunteer_id=<freshly_created_volunteer_id>, 
                         interest_area_id=area_id)
                        for area_id in areas
                      ])

        return volunteer