10

我正在使用 django-rest-framework 来构建后端。我的列表运行良好,但是(使用 django-rest-framework 管理屏幕)我不能仅使用外键对象的 Id 字段来创建对象。我希望我的配置不正确,但如果我不得不写一些代码,我愿意:) 我正在从 .NET 和 Java 背景学习 django/python,并且可能已经被这个新堆栈宠坏了。

编辑:我试图不使用两个不同的模型类——我不应该这样做吗?

提前致谢。

来自 Chrome - 请求的关键位

Request URL:http://127.0.0.1:8000/rest/favorite_industries/ 
Request Method:POST 
_content_type:application/json
_content:{
    "user_id": 804    ,"industry_id": 20 }

响应

HTTP 400 BAD REQUEST
Vary: Accept
Content-Type: text/html; charset=utf-8
Allow: GET, POST, HEAD, OPTIONS

{
    "user": [
        "This field is required."
    ]
}

啊。以下是 django 的关键类:

class FavoriteIndustry(models.Model):
    id = models.AutoField(primary_key=True)
    user = models.ForeignKey(User, related_name='favorite_industries')
    industry = models.ForeignKey(Industry)

    class Meta:
        db_table = 'favorites_mas_industry'

class FavoriteIndustrySerializer(WithPkMixin, serializers.HyperlinkedModelSerializer):
    class Meta:
        model = myModels.FavoriteIndustry
        fields = (
            'id'
            , 'user'
            , 'industry'
        )

编辑添加视图集:

class FavoriteIndustriesViewSet(viewsets.ModelViewSet):
    #mixins.CreateModelMixin, viewsets.GenericViewSet):
    paginate_by = 1
    queryset = myModels\
        .FavoriteIndustry\
        .objects\
        .select_related()
    print 'SQL::FavoriteIndustriesViewSet: ' + str(queryset.query)
    serializer_class = mySerializers.FavoriteIndustrySerializer

get/list 功能生成不错的 JSON:

{“计数”:2,“下一个”:“ http://blah.com/rest/favorite_industries/?page=2&format=json ”,“上一个”:空,“结果”:[{“id”:1, “用户”:“ http://blah.com/rest/users/804/ ”,“行业”:{“industry_id”:2,“industry_name”:“消费者自由裁量权”,“parent_industry_name”:“消费者自由裁量权”, "category_name": "行业"}}]}

4

2 回答 2

40

我创建了您的应用程序的简化模型。

模型.py:

from django.db import models
from django.contrib.auth.models import User

class Industry(models.Model):
    name = models.CharField(max_length=128)

class FavoriteIndustry(models.Model):
    user = models.ForeignKey(User, related_name='favorite_industries')
    industry = models.ForeignKey(Industry)

视图.py:

from rest_framework import viewsets
from models import FavoriteIndustry
from serializers import FavoriteIndustrySerializer

class FavoriteIndustriesViewSet(viewsets.ModelViewSet):
    queryset = FavoriteIndustry.objects.all()
    serializer_class = FavoriteIndustrySerializer

序列化程序.py:

from rest_framework import serializers
from models import FavoriteIndustry, Industry

class FavoriteIndustrySerializer(serializers.HyperlinkedModelSerializer):
    class Meta:
        model = FavoriteIndustry
        fields = ('id', 'user', 'industry')

网址.py:

from django.conf.urls import patterns, include, url
from core.api import FavoriteIndustriesViewSet

favorite_industries_list = FavoriteIndustriesViewSet.as_view({
    'get': 'list',
    'post': 'create'
})

urlpatterns = patterns('',
    url(r'^favorite_industries/$', favorite_industries_list, name='favorite-industries-list'),
    url(r'^users/(?P<pk>[0-9]+)/$', favorite_industries_list, name='user-detail'),
    url(r'^industries/(?P<pk>[0-9]+)/$', favorite_industries_list, name='industry-detail'),
)

这里有一些测试:

>>> 
>>> import json
>>> from django.test import Client
>>> from core.models import Industry
>>> 
>>> industry = Industry(name='candy')
>>> industry.save()
>>> 
>>> c = Client()
>>> 
>>> response = c.get('http://localhost:8000/favorite_industries/')
>>> response.content
'[]'
>>> 
>>> data = {
...     'user': 'http://localhost:8000/users/1/',
...     'industry': 'http://localhost:8000/industries/1/'
... }
>>> 
>>> response = c.post('http://localhost:8000/favorite_industries/', json.dumps(data), 'application/json')
>>> response.content
'{"id": 1, "user": "http://testserver/users/1/", "industry": "http://testserver/industries/1/"}'
>>> 
>>> response = c.get('http://localhost:8000/favorite_industries/')
>>> response.content
'[{"id": 1, "user": "http://testserver/users/1/", "industry": "http://testserver/industries/1/"}]'
>>> 

由于您使用的user是.industryHyperlinkedModelSerializer


使用 ID

如果您需要使用对象 ID 而不是 URL,请使用ModelSerializer代替HyperlinkedModelSerializer并将 ID 传递给userand industry

序列化程序.py:

from rest_framework import serializers
from models import FavoriteIndustry, Industry

class FavoriteIndustrySerializer(serializers.ModelSerializer):
    class Meta:
        model = FavoriteIndustry
        fields = ('id', 'user', 'industry')

和测试:

>>> 
>>> import json
>>> from django.test import Client
>>> from core.models import Industry
>>> 
>>> #industry = Industry(name='candy')
>>> #industry.save()
>>> 
>>> c = Client()
>>> 
>>> response = c.get('http://localhost:8000/favorite_industries/')
>>> response.content
'[{"id": 1, "user": 1, "industry": 1}, {"id": 2, "user": 1, "industry": 1}]'
>>> 
>>> data = {
...     'user': 1,
...     'industry': 1
... }
>>> 
>>> response = c.post('http://localhost:8000/favorite_industries/', json.dumps(data), 'application/json')
>>> response.content
'{"id": 3, "user": 1, "industry": 1}'
>>> 
>>> response = c.get('http://localhost:8000/favorite_industries/')
>>> response.content
'[{"id": 1, "user": 1, "industry": 1}, {"id": 2, "user": 1, "industry": 1}, {"id": 3, "user": 1, "industry": 1}]'
>>> 
于 2013-10-16T21:39:12.140 回答
0

这会做到的。但我认为 django-rest-framework 应该为我提供这种管道,所以请跟进任何更好的答案

class FavoriteIndustriesViewSet(mixins.ListModelMixin, viewsets.GenericViewSet):
    paginate_by = 1
    queryset = myModels\
        .FavoriteIndustry\
        .objects\
        .select_related()
    print 'SQL::FavoriteIndustriesViewSet: ' + str(queryset.query)
    serializer_class = mySerializers.FavoriteIndustrySerializer

    def create(self, request):
        print(request.DATA)
        user_id = request.DATA['user_id']
        industry_id = request.DATA['industry_id']
        favorite = myModels.FavoriteIndustry(user_id=user_id, industry_id=industry_id)
        favorite.save()
        responseData = {
            'user_id': user_id
            , 'industry_id': industry_id
            , 'message': 'FavoriteIndustry saved.'
        }
        return Response(responseData)
于 2013-10-16T19:13:05.413 回答