我使用django-models-utils是为了获取一个类的所有子类。我已经成功地做到了这一点,但现在我似乎不能获得仅有父类的视图。
这是主类,其他类用于复习:
class Post(models.Model):
author = models.ForeignKey(User, null=True, blank=True)
title = models.CharField(max_length=200)
slug = models.SlugField(max_length=200, unique=True, blank=True)
text = models.TextField()
notable = models.BooleanField(default=False)
created = models.DateTimeField(editable=False, auto_now_add=True)
published = models.DateTimeField(null=True, blank=True)
modified = models.DateTimeField(editable=False, auto_now=True)
tags = models.ManyToManyField(Tag, blank=True)
objects = InheritanceManager()这是所有帖子(包括孩子)的视图,它正在工作:
def all_posts(request):
posts = Post.objects.order_by('published').filter(published__lte=timezone.now()).select_subclasses()
return render(request, 'blog/post_list.html', {'posts': posts})这只是帖子的视图(不是评论,也不是孩子),但这并不起作用,因为我得到了所有的帖子:
class RamblingList(ListView):
context_object_name = 'ramblings'
queryset = Post.objects.filter(published__lte=timezone.now()).order_by('published')
template_name = 'blog/rambling_list.html' 有人能告诉我我哪里做错了吗?
发布于 2015-09-02 04:30:47
InheritanceManager不应该这样做。如果在没有调用select_subclasses()的情况下调用任何过滤器,它将返回所有没有子类强制转换的对象。
这一点在文档中很清楚:http://django-model-utils.readthedocs.org/en/latest/managers.html#inheritancemanager
但是当你遍历nearby_places时,你只能得到
实例,即使是那些“真正的”餐馆或酒吧的对象也是如此
你可以这样做来达到想要的效果:
queryset = Post.objects.filter(
published__lte=timezone.now()
).order_by('published').select_subclasses()
queryset = [x for x in queryset if type(x) == Post]https://stackoverflow.com/questions/32339818
复制相似问题