gpt4 book ai didi

python - 在 Django 的自定义管理器中面临问题

转载 作者:行者123 更新时间:2023-12-02 16:08:18 24 4
gpt4 key购买 nike

我正在尝试创建一个自定义管理器来检索所有状态为已发布 的帖子。管理人员的新手!!提前谢谢你 <3.

模型.py


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


class Post(models.Model):
STATUS_CHOICES = (
('draft', 'Draft'),
('published', 'Published'),
)
title = models.CharField(max_length=255)
slug = models.SlugField(max_length=255, unique_for_date='publish')
author = models.ForeignKey(
User, on_delete=models.CASCADE, related_name='blog_posts')
body = models.TextField()
publish = 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')
objects = models.Manager()
published = PublishedManager()

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

def __str__(self):
return self.title

def get_absolute_url(self):
return reverse('blog:post_detail', args=[self.publish.year, self.publish.month, self.publish.day, self.slug])

View .py

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


def post_detail(request):
post = get_object_or_404(Post, slug=post, status='published',
publish__year=year, publish__month=month, publish__day=day)

return render(request, 'post/detail.html', {'post': post})

错误

'PublishedManager' object has no attribute 'all' (views.py, line 6, in post_list)

最佳答案

您应该使用 Manager 作为管理器的基类,而不是 Model。并且方法名称应该是 get_queryset 而不是 get_query_set:

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

您可以在 docs 中找到更多详细信息.

关于python - 在 Django 的自定义管理器中面临问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/68742029/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com