【发布时间】:2015-07-01 21:18:50
【问题描述】:
我是 django 新手,我按照本教程创建了一个 django 应用程序:http://www.django-rest-framework.org/tutorial/quickstart/
本教程提供了一个包含各种字段的预制用户类。我正在尝试添加一个可以通过 android 中的 PUT 请求频繁更新的自定义 DateTimeField。如何将此自定义字段“时间戳”添加到此类。
这是我的代码:
序列化器.py
from django.contrib.auth.models import User
from rest_framework import serializers
from django.contrib.auth.models import models
class UserSerializer(serializers.HyperlinkedModelSerializer):
class Meta:
model = User
lookup_field = 'username'
set_timezone = 'date_joined'
fields = ('url', 'username','date_joined')
Views.py
from django.contrib.auth.models import User
from rest_framework import viewsets
from tutorial.quickstart.serializers import UserSerializer
from django.conf import settings
from django.shortcuts import redirect, render
dir(settings)
settings.__dict__
class UserViewSet(viewsets.ModelViewSet):
"""
API endpoint that allows users to be viewed or edited.
"""
lookup_field = 'username'
queryset = User.objects.all()
serializer_class = UserSerializer
urls.py
from django.conf.urls import url, include
from rest_framework import routers
from tutorial.quickstart import views
router = routers.DefaultRouter()
router.register(r'users', views.UserViewSet)
urlpatterns = [
url(r'^', include(router.urls)),
url(r'^api-auth/', include('rest_framework.urls', namespace='rest_framework'))
]
模型.py
from django.db import models
# Create your models here.
from datetime import datetime
class Time(models.Model):
timestamp = models.DateTimeField(auto_now_add=True)
def __unicode__(self):
return "Time"
错误
异常值:
字段名称timestamp对模型User无效。 异常位置:/Library/Python/2.7/site-packages/rest_framework/serializers.py in build_unknown_field,第 1079 行 Python 可执行文件:/Library/Frameworks/Python.framework/Versions/2.7/Resources/Python.app/Contents/MacOS/Python Python 版本:2.7.6
【问题讨论】:
-
timestamp只是您的用户模型上的自定义字段吗? -
@KevinBrown 是的,我正在尝试创建这个名为时间戳的自定义 DateTimeField。
-
您是否尝试将其添加到序列化程序元中的
fields? -
@KevinBrown 是的,我得到一个错误,因为我认为我需要为它创建一个视图和模型,但我不确定如何实现它。
-
请在您的问题中包含错误和您的模型。
标签: android python django django-models django-rest-framework