我是Django的初学者,特别是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 / users以检查我的用户是否添加良好时,我的设置字段为空
我不明白这是什么问题
答案 0 :(得分:0)
在serializers.py
文件中,您必须先添加settings
和address
才能创建用户对象。
所以替换这个:
user = User.objects.create(**validated_data)
user.address = address
user.settings = settings
by:
validated_data['address'] = address;
validated_data['settings'] = settings;
user = User.objects.create(**validated_data)