django restframework - 用于创建m2m关系的序列化器 [英] django restframework - Serializer for creating m2m relationship

查看:236
本文介绍了django restframework - 用于创建m2m关系的序列化器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在为我的API使用 django-restframework 。我创建了一个序列号,它应该列出我的对象,并且应该可以创建它们。



我有一个联系人实体和产品喜欢之间有一个标准的m2m。



这是我的模型:

  class Contact(models.Model):
...
products_of_interest = models.ManyToManyField(Product,related_name = \"interest_contacts)

我的序列化器很简单:

  class ContactSerializer(serializers.ModelSerializer):

class Meta:
model = Contact
/ pre>

当我通过这个序列号列出我的联系人时,我得到所有我的联系对象与一系列的产品ids - awesome:

 products_of_interest:[
1,
2
]

现在,当我想创建一个联系人并填充m2m时,我得到以下内容(通过我的Chrome邮递员和表单数据):




  • 发送products_of_interest = 1 - >作品(!!!),只是一个产品!

  • 发送商品ts_of_interest = [1,2] - >需要pk而不是unicode

  • 发送products_of_interest = 1; 2 - >需要pk而不是unicode

  • 发送products_of_interest [0] = 1,products_of_interest [1] = 2 - >什么都没有完成



我有一些经验与序列化器,所以我想,也许我需要告诉序列化器,我想给他多个产品。所以我把它添加到我的序列化器中:

  products_of_interest = ProductSerializer(many = True,required = False,read_only = False)

现在我收到这个错误:


<联系人:>在这种多对多关系可以使用之前,需要有一个字段联系的值。


我完全失去了现在。我能做什么?不能,我需要覆盖标准的rfw函数来保存一个简单的m2m,可以吗?



谢谢!



Ron

解决方案

你使用什么版本的Django和drf?我无法使用Django 1.7和drf 2.4.2重现错误。这是我的代码:



models.py

  from django.db导入模型

class Product(models.Model):
pass


class Contact(models.Model):
products_of_interest = models .ManyToManyField(Product,
related_name = \"interest_contacts)

serializers.py

  from .models import联系
从rest_framework import serializers


class ContactSerializer(serializers .ModelSerializer):
class Meta:
model =联系人

views.py

从rest_framework导入视图
从.models import联系
从.serializers import ContactSerializer

class ContactViewSet(viewsets.ModelViewSet):
queryset = Contact.objects.all()
serializer_class = ContactSerializer

urls.py

 从django.conf .urls import include,url 

from rest_framework import router
from。导入视图

router = routes.DefaultRouter()
router.register(r'contacts',views.ContactViewSet,'contacts')
urlpatterns = router.urls

urlpatterns = [
url(r'^',include(router.urls)),
url(r'^ api-auth /',include('rest_framework.urls' namespace ='rest_framework'))
]

./manage.py shell
>>>从m2m_test.models import product
>>>对于我在范围(3):Product.objects.create()
...
<产品:产品对象>
<产品:产品对象>
<产品:产品对象>
>>>

然后在网页前端 http:// localhost:8000 /联系人/



使用原始数据形式的POST:
{
products_of_interest:[1,2,3 ]
}



- >只是工作。


I am using django-restframework for my API. I created a serializer which should list my objects and should be able to create them.

I have a Contact entity and Product. There is a standard m2m between it for the likes.

Here's my model:

class Contact(models.Model):
    ...
    products_of_interest = models.ManyToManyField(Product, related_name="interested_contacts")

My serializer is as simple as it gets:

class ContactSerializer(serializers.ModelSerializer):

    class Meta:
        model = Contact

When I list my contacts via this serializer I get all my contact objects with an array of product ids - awesome:

"products_of_interest": [
        1,
        2
    ]

Now, when I want to create a contacts and populate the m2m, I get the following (via my Chrome Postman and form-data):

  • Send products_of_interest = 1 --> works (!!!) but just for one product!
  • Send products_of_interest = [1,2] --> needs pk and not unicode
  • Send products_of_interest = 1;2 --> needs pk and not unicode
  • Send products_of_interest[0] = 1, products_of_interest[1] = 2 --> nothing is done at all

I have some experience with serializers, so I thought, maybe I need to tell the serializer, that I want to give him more than one product. So I added this in my serializer:

products_of_interest = ProductSerializer(many=True, required=False, read_only=False)

Now I get this error:

"<Contact: >" needs to have a value for field "contact" before this many-to-many relationship can be used.

I'm totally lost now. What can I do? It can't be that I need to override standard rfw-functions for saving a damn easy m2m, can it?

Thanks!

Ron

解决方案

What version of Django and drf are you using? I cannot reproduce your errors using Django 1.7 and drf 2.4.2. Here's my code:

models.py

from django.db import models

class Product(models.Model):
    pass


class Contact(models.Model):
    products_of_interest = models.ManyToManyField(Product,
        related_name="interested_contacts")

serializers.py

from .models import Contact
from rest_framework import serializers


class ContactSerializer(serializers.ModelSerializer):
    class Meta:
        model = Contact

views.py

from rest_framework import viewsets
from .models import Contact
from .serializers import ContactSerializer

class ContactViewSet(viewsets.ModelViewSet):
    queryset = Contact.objects.all()
    serializer_class = ContactSerializer

urls.py

from django.conf.urls import include, url

from rest_framework import routers
from . import views

router = routers.DefaultRouter()
router.register(r'contacts', views.ContactViewSet, 'contacts')
urlpatterns = router.urls

urlpatterns = [
    url(r'^', include(router.urls)),
    url(r'^api-auth/', include('rest_framework.urls', namespace='rest_framework'))
]

./manage.py shell
>>> from m2m_test.models import Product
>>> for i in range(3): Product.objects.create()
...
<Product: Product object>
<Product: Product object>
<Product: Product object>
>>>

And then in the web frontend at http://localhost:8000/contacts/:

POST with Raw Data form: { "products_of_interest": [1, 2, 3] }

-> just works.

这篇关于django restframework - 用于创建m2m关系的序列化器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆