Django View -如何有效地从多个模型中过滤组合查询集?

2skhul33  于 2023-08-08  发布在  Go
关注(0)|答案(1)|浏览(88)

我有一个Django视图,它组合和排序来自三个不同模型(事件,主题和文章)的查询集来创建一个提要。我使用sorted函数沿着chain合并查询集,并根据'created_at'属性对它们进行排序。然后,提要作为列表返回。
然而,当涉及到根据用户提供的搜索和作者参数来过滤提要时,我面临着挑战。因为feed是列表形式的,所以我不能直接使用Django QuerySet中的filter方法。
created_by__username__icontains不工作。只有ModelChoiceField与它沿着工作,但希望与它一起使用CharField字段。
forms.py

class FeedFilterForm(forms.Form):
    author = forms.CharField( # ModelChoiceField
        label='Author',
        required=False,
        # queryset=User.objects.all(),
        widget=forms.TextInput(attrs={'placeholder': 'Author'}),
    )

字符串
Views.py

class FeedView(View):
    form_class = FeedFilterForm
    template_name = 'your_template.html'

    def get_queryset(self):
        """
        Get the combined and sorted queryset from events, subjects, and articles.
        """
        events = Event.objects.all()
        subjects = Subject.objects.all()
        articles = Article.objects.all()

        feed = sorted(
            chain(articles, subjects, events),
            key=attrgetter('created_at'),
            reverse=True,
        )

        form = self.form_class(self.request.GET)

        if form.is_valid():
            data = form.cleaned_data

            author = data.get('author')
            if author:
                feed = filter(
                    lambda x: author
                    == getattr(x, 'created_by__username__icontains', ''),
                    feed,
                )

        return list(feed)

    def get(self, request, *args, **kwargs):
        queryset = self.get_queryset()

        context = {
            'object_list': queryset,
        }

        return render(request, self.template_name, context)

n7taea2i

n7taea2i1#

在调用sorted()之前,您需要过滤查询集。将逻辑移至get_queryset(),忽略filter_queryset()

def get_queryset(self):
    """
    Get the combined and sorted queryset from events, subjects, and articles.
    """
    events = Event.objects.all()
    subjects = Subject.objects.all()
    articles = Article.objects.all()

    # Insert your filter logic here

    feed = sorted(
        chain(articles, subjects, events),
        key=attrgetter('created_at'),
        reverse=True,
    )

    queryset = self.filter_queryset(feed)
    return list(queryset)

字符串
顺便说一句,我不明白你为什么要写

getattr(x, 'created_by__username__icontains', '')


created_by__username__icontains在这里没有任何意义。

相关问题