AttributeError-'DeferredAttribute'对象没有属性'all'

时间:2019-01-20 06:13:34

标签: django python-3.x django-models django-views attributeerror

我在posts = Post.published.all()中不断收到错误消息

models.py

from django.db import models
from django.utils import timezone
from django.contrib.auth.models import User
from django.urls import reverse


class Post(models.Model):
STATUS_CHOICES = (
     ('draft','Draft'),
     ('published','Published'),
)
title = models.CharField(max_length=250)
slug = models.SlugField(max_length=250,
                         unique_for_date='published')
author = models.ForeignKey(User,
                           related_name='blog_posts',
                           on_delete=models.CASCADE)
body = models.TextField()
published = models.DateTimeField(default=timezone.now)
created = models.DateTimeField(auto_now_add=True)
updated = models.DateTimeField(auto_now=True)
status = models.CharField(max_length=10,
                          choices = STATUS_CHOICES,
                          default='draft')
def get_absolute_url(self):
    return reverse('blog:post_detail',
                   args=[self.publish.year,
                         self.publish.strftime('%m'),
                         self.publish.strftime('%d'),
                         self.slug])

class Meta:
    ordering = ('-published',)


def __str__(self):
    return self.title  

views.py

from django.shortcuts import render, get_object_or_404
from .models import Post

def post_list(request):
posts = Post.published.all()
return render(request,
              'blog/post/list.html',
              {'posts': posts})

def post_detail(request, year, month, day, post):
post = get_object_or_404(Post, slug=post,
                               status='published',
                               publish_year=year,
                               publish_month=month,
                               publish_day=day)

每当我运行服务器时,我都会不断收到此错误...

AttributeError at /blog/ 'DeferredAttribute' object has no attribute 'all'

from django.shortcuts import render, get_object_or_404
from .models import Post
def post_list(request):
posts = Post.published.all() ...

另外一些有关创建自己的博客页面的技巧也将有所帮助

3 个答案:

答案 0 :(得分:1)

您需要使用tf.reduce_sum(input1 * tf.one_hot(input2, y), 2)代替objects

published

如果您要过滤posts = Post.objects.all() 个帖子,请使用此选项:

published

答案 1 :(得分:0)

要使其与自定义发布管理器一起使用,请将其添加到模型文件中的post类之上。

class PublishedManager(models.Manager):
    def get_queryset(self):
        return super(PublishedManager,
        self).get_queryset().filter(status='published')

然后将管理器添加到Post类中

published = PublishedManager()

答案 2 :(得分:0)

获取所有帖子:

posts = Post.objects.all() 

要获取已发布的帖子:

posts = Post.objects.filter(status='published')