类型对象“问题”没有属性“对象”

时间:2018-07-23 08:51:44

标签: python django

我是django的新手,当我从文档.d中学习django时,我尝试使用序列化程序和基于函数的视图制作api。这表明类型object'Questions'没有属性'objects

models.py

class Questions:
    title = models.CharField(max_length=40)
    description = models.TextField(max_length=50)
    status = models.CharField(default='inactive', max_length=30)
    created_by = models.ForeignKey(User, null=True, blank=True, on_delete=models.CASCADE

serializers.py

from rest_framework import serializers
from demoapp.models import Questions


class QuestionSerializer(serializers.ModelSerializer):
    class Meta:
        model = Questions
        fields = (
            'id',
            'title',
            'description',
            'created_by',

        )

urls.py

from django.urls import path
from demoapp.views import *

urlpatterns = [
    path('poll', demoapp),
]

views.py

from django.shortcuts import render
from rest_framework import viewsets
from demoapp.models import Questions
from demoapp.serializers import QuestionSerializer
from django.http import JsonResponse

def demoapp(request):
    if request.method=="GET":
        queryset=Questions.objects.all()
        serializer=QuestionSerializer(snippets)
        return JsonResponse(serializer.data,safe=False)

2 个答案:

答案 0 :(得分:3)

您应该从Django models.Model继承模型类:

from django.db import models

class Questions(models.Model):

在进行此更改之后,您应该进行并应用迁移,请阅读文档:migrations commands(感谢@Willem Van Onsem的评论)。

答案 1 :(得分:-1)

在您的模型中,您没有结束括号:

created_by = models.ForeignKey(User, null=True, blank=True, on_delete=models.CASCADE

它应该像这样:

created_by = models.ForeignKey(User, null=True, blank=True, on_delete=models.CASCADE)

您可能没有导入用户

from django.contrib.auth.models import User

您可以尝试进行迁移