2014-12-27 75 views
1

我與Django和特意用Django的REST框架初學者。 我正試圖發佈一個包含用戶設置的新用戶。無法發佈OneToOneField Django的REST

這是我的models.py

from django.db import models 
from datetime import datetime 
from pygments.lexers import get_all_lexers 
from pygments.styles import get_all_styles 

LEXERS = [item for item in get_all_lexers() if item[1]] 
LANGUAGE_CHOICES = sorted([(item[1][0], item[0]) for item in LEXERS]) 
STYLE_CHOICES = sorted((item, item) for item in get_all_styles()) 

class Address(models.Model): 
    number = models.IntegerField(null=True) 
    streetName = models.CharField(max_length=50, default=None, null=True) 
    zipCode = models.IntegerField(default=None, null=True) 
    city = models.CharField(max_length=50, default=None, null=True) 
    country = models.CharField(max_length=50, default=None, null=True) 

class Settings(models.Model): 
    cancelTime = models.IntegerField(default=5) 
    onlyInWifi = models.BooleanField(default=False) 

class User(models.Model): 
    firstName = models.CharField(max_length=100) 
    lastName = models.CharField(max_length=100) 
    pseudo = models.CharField(max_length=100, default=None) 
    mail = models.CharField(max_length=100) 
    password = models.CharField(max_length=250) 
    address = models.ForeignKey(Address, null=True) 
    settings = models.OneToOneField(Settings, null=True) 

這是我serializers.py

from rest_framework import serializers 
from api.models import User 
from api.models import Address 
from api.models import Settings 


class AddressSerializer(serializers.ModelSerializer): 
    class Meta: 
     model = Address 
     fields = ('number', 'streetName', 'zipCode', 'city', 'country') 

class SettingsSerializer(serializers.ModelSerializer): 
    class Meta: 
     model = Settings 
     fields = ('cancelTime', 'onlyInWifi') 

class UserSerializer(serializers.ModelSerializer): 
    address = AddressSerializer(required=False) 
    settings = SettingsSerializer(required=False) 

    class Meta: 
     model = User 
     fields = ('pk','firstName', 'lastName', 'pseudo', 'mail', 'password', 'settings', 'address') 

    def create(self, validated_data): 
     if(validated_data.get('address')): 
      address_data = validated_data.pop('address') 
      address = Address.objects.create(**address_data) 
     else: 
      address = None 

     if(validated_data.get('settings')): 
      settings_data = validated_data.pop('settings') 
      settings = Settings.objects.create(**settings_data) 
     else: 
      settings = Settings() 

     user = User.objects.create(**validated_data) 
     user.address = address 
     user.settings = settings 
     return user 

這是我的urls.py

from django.conf.urls import patterns, url 

urlpatterns = patterns(
    'api.views', 

    #Users 
    url(r'^users/$', 'users_list', name='users_list'), 
    url(r'^users/(?P<pk>[0-9]+)$', 'user_detail', name='user_detail'), 
} 

這是我views.py

import logging 

from rest_framework import status 
from rest_framework.decorators import api_view 
from rest_framework.response import Response 

from api.models import User 
from api.serializers import UserSerializer 

#Users 
@api_view(['GET', 'POST']) 
def users_list(request): 
    """ 
    List all users, or create a new user. 
    """ 
    if request.method == 'GET': 
     users = User.objects.all() 
     serializer = UserSerializer(users, many=True) 
     return Response(serializer.data) 

    elif request.method == 'POST': 
     serializer = UserSerializer(data=request.DATA) 
     if serializer.is_valid(): 
      serializer.save() 
      return Response(serializer.data, status=status.HTTP_201_CREATED) 
     else: 
      return Response(
       serializer.errors, status=status.HTTP_400_BAD_REQUEST) 


@api_view(['GET', 'PUT', 'DELETE']) 
def user_detail(request, pk): 
    """ 
    Get, udpate, or delete a specific user 
    """ 
    try: 
     user = User.objects.get(pk=pk) 
    except User.DoesNotExist: 
     return Response(status=status.HTTP_404_NOT_FOUND) 

    if request.method == 'GET': 
     serializer = UserSerializer(user) 
     return Response(serializer.data) 

    elif request.method == 'PUT': 
     serializer = UserSerializer(user, data=request.DATA, partial=True) 
     if serializer.is_valid(): 
      serializer.save() 
      return Response(serializer.data) 
     else: 
      return Response(
       serializer.errors, status=status.HTTP_400_BAD_REQUEST) 

    elif request.method == 'DELETE': 
     user.delete() 
     return Response(status=status.HTTP_204_NO_CONTENT) 

當我嘗試發佈一個新的用戶,我有我想

但是當我加載API /用戶檢查,如果我的用戶良好補充,我的設置字段爲null,則行爲

我不明白是什麼問題

+0

你可以添加代碼示例顯示您發佈的是什麼?另外,你的'User'模型允許'settings'爲null,這是否正確? – 2014-12-29 10:54:36

+0

是我的設置,可以爲空,但例如當我張貼此: { 「名字」: 「firstNameTest」, 「姓氏」: 「lastNameTest」, 「僞」: 「pseudoTest」, 「郵件」: 「[email protected]」, 「密碼」: 「testPass」, 「user_settings」:{ 「cancelTime」:50, 「onlyInWifi」:真 } } 我有我想要的行爲,但當我加載api /用戶時,我的設置在我剛剛添加的用戶對象中爲空 – 2014-12-30 13:25:09

回答

0

serializers.py文件中,您必須先添加您的settingsaddress才能創建您的用戶對象。

所以替換此:

user = User.objects.create(**validated_data) 
user.address = address 
user.settings = settings 

由:

validated_data['address'] = address; 
validated_data['settings'] = settings; 
user = User.objects.create(**validated_data)