如何在Django通用视图中添加额外的上下文和查询集字段?

she*_*sky 2 django django-queryset django-views django-generic-views django-context

我正在构建Django应用程序,提交链接和投票功能.

我想显示所有链接,由用户在用户详细信息页面中投票.我可以使用以下方法在python shell中检索它们:

Link.objects.filter(votes__voter=user)
Run Code Online (Sandbox Code Playgroud)

但我不知道如何将此作为额外的上下文字段添加到视图中.以下是代码:

models.py

class Link(models.Model):
    title       = models.CharField(max_length=200)
    submitter   = models.ForeignKey(User)
    submit_date = models.DateTimeField(auto_now_add=True)
    up_votes    = models.IntegerField(default=0, blank=True, db_index=True)
    ...

class UserProfile(models.Model):
    user        = models.OneToOneField(User, unique=True)
    ...

class Vote(models.Model):
    voter = models.ForeignKey(User)
    link = models.ForeignKey(Link, related_name='votes')
    ...
Run Code Online (Sandbox Code Playgroud)

views.py

class UserProfileDetailView(DetailView):
    model       = get_user_model()
    slug_field  = "username"
    template_name = "user_detail.html"


    def get_object(self, queryset=None):
        user    = super(UserProfileDetailView, self).get_object(queryset)s
        UserProfile.objects.get_or_create(user=user)
        return user
Run Code Online (Sandbox Code Playgroud)

user_detail.html

...
{% if object == request.user and request.user.is_authenticated %}
    <p><a href='{% url "edit_profile" %}'>Edit My Profile</a></p>
{% endif %}

{% if link in voted_list %}
    <p><a href='{% url "link_detail" %}'>{{ link.title }}</a></p>
{% endif %}
...
Run Code Online (Sandbox Code Playgroud)

我无法弄清楚如何根据链接实现添加额外字段.我不知道我需要定义新的查询集,定义新对象或只指向新的上下文.如果你能为我点亮这一点,我将不胜感激.

Rah*_*pta 9

您可以覆盖您的get_context_data()功能UserProfileDetailView以添加额外的上下文.

在这里,我们将添加一个额外的变量voted_links,其中包含当前用户投票的所有链接.

class UserProfileDetailView(DetailView):     

    def get_context_data(self, **kwargs):
        context = super(UserProfileDetailView, self).get_context_data(**kwargs) # get the default context data
        context['voted_links'] = Link.objects.filter(votes__voter=self.request.user) # add extra field to the context
        return context
Run Code Online (Sandbox Code Playgroud)