在django queryset中匹配可选字段中的空白条目以及必填字段中的相应字段

时间:2010-04-08 21:48:37

标签: python django

我的视图中有一个django查询集,其值在我传递给模板之前打包。查询集返回none时出现问题,因为关联的值未解包。 quersyet被称为comments

这是我的views.py

def forums(request ):


post_list = list(forum.objects.filter(child='0')&forum.objects.filter(deleted='0').order_by('postDate'))
user = UserProfile.objects.get(pk=request.session['_auth_user_id'])
newpostform = PostForm(request.POST)
deletepostform = PostDeleteForm(request.POST)
DelPostFormSet = modelformset_factory(forum, exclude=('child','postSubject','postBody','postPoster','postDate','childParentId'))
readform = ReadForumForm(request.POST)
comments =list( forum.objects.filter(deleted='0').filter(child='1').order_by('childParentId').values('childParentId').annotate(y=Count('childParentId')))


if request.user.is_staff== True :
    staff = 1
else:
    staff = 0
staffis = 1




if newpostform.is_valid():
    topic = request.POST['postSubject']
    poster = request.POST['postPoster']
    newpostform.save()
    return HttpResponseRedirect('/forums')

else:
    newpostform = PostForm(initial = {'postPoster':user.id})

if request.GET:
    form = SearchForm(request.GET)
    if form.is_valid():
        query = form.cleaned_data['query']
        post_list = list((forum.objects.filter(child='0')&forum.objects.filter(deleted='0')&forum.objects.filter(Q(postSubject__icontains=query)|Q(postBody__icontains=query)|Q(postDate__icontains=query)))or(forum.objects.filter(deleted='0')&forum.objects.filter(Q(postSubject__icontains=query)|Q(postBody__icontains=query)|Q(postDate__icontains=query)).values('childParentId')))

if request.method == 'POST':
    delpostformset = DelPostFormSet(request.POST)
    if delpostformset.is_valid():
        delpostformset.save()
        return HttpResponseRedirect('/forums')

else:
    delpostformset = DelPostFormSet(queryset=forum.objects.filter(child='0', deleted='0'))



"""if readform.is_valid():
    user=get_object_or_404(UserProfile.objects.all())
    readform.save()
else:
    readform = ReadForumForm()"""

post= zip( post_list,comments, delpostformset.forms)
paginator = Paginator(post, 10) # Show 10 contacts per page

# Make sure page request is an int. If not, deliver first page.
try:
    page = int(request.GET.get('page', '1'))
except ValueError:
    page = 1

# If page request (9999) is out of range, deliver last page of results.
try:
    post = paginator.page(page)
except (EmptyPage, InvalidPage):
    post = paginator.page(paginator.num_pages)

return render_to_response('forum.html', {'post':post, 'newpostform': newpostform,'delpost':delpostformset, 'username':user.username, 'comments':comments, 'user':user,  },context_instance = RequestContext( request ))

我意识到问题出在comments查询集comments =list( forum.objects.filter(deleted='0').filter(child='1').order_by('childParentId').values('childParentId').annotate(y=Count('childParentId'))),它只会返回有评论的帖子的值。所以当post-list post_list = list(forum.objects.filter(child='0')&forum.objects.filter(deleted='0').order_by('postDate'))中的值没有任何注释(可选字段)时,我现在需要一种方法来返回0条评论。

这是我的models.py

class forum(models.Model):
    postID = models.AutoField(primary_key=True)
    postSubject = models.CharField(max_length=100)
    postBody = models.TextField()
    postPoster = models.ForeignKey(UserProfile)
    postDate =  models.DateTimeField(auto_now_add=True)
    child = models.BooleanField()
    childParentId = models.ForeignKey('self',blank=True, null=True)
    deleted = models.BooleanField()

    def __unicode__(self):
        return u' %d' % ( self.postID)

2 个答案:

答案 0 :(得分:3)

你可以这样做:

comments = list(queryset or [])

如果查询集解析为None,则将使用空列表,comments将只是一个空列表。

答案 1 :(得分:0)

我认为你做得不对。我不相信queryset可以返回None。为什么不直接链接filter方法?

list(forum.objects.filter(child='0').filter(deleted='0').order_by('postDate'))

如果您有更复杂的查询,可以使用django的Query objects,这样您就可以使用&|逻辑运算符。