【问题标题】:Django - Accessing Model Field in class based viewDjango - 在基于类的视图中访问模型字段
【发布时间】:2021-06-28 00:16:44
【问题描述】:

我有这个模型

class Post(models.Model):
    title = models.CharField(max_length=100)
    title2 = models.CharField( max_length=100)
    content = models.TextField(default=timezone.now)
    content2 = models.TextField(default=timezone.now)
    post_image = models.ImageField(upload_to='post_pics')
    post_image2 = models.ImageField(upload_to='post2_pics')
    date_posted = models.DateTimeField(default=timezone.now)
    author = models.ForeignKey(User, on_delete=models.CASCADE)

以及使用该模型的基于函数的视图:

class PostListView(ListView):
    model = Post
    template_name = 'front/front.html'
    context_object_name = 'listings'
    ordering = ['-date_posted']
    
    def get_context_data(self, **kwargs):
        check_for_zipcode = #where I want to access the author for the current instance 
        context = super().get_context_data(**kwargs)
        context['zipcodes'] = check_for_zipcode
        return context

我只想知道如何在基于类的视图中访问author 字段。我可以像这样在我的 HTML 中访问作者”

{% for listings in listings %}
  
  <h3>listings.author</h3>
    
{% endfor %}

这样,我将为该模型的每个实例取回 author 字段。

如何获取变量check_for_zipcode 中实例的作者?我试过self.authorself.listings.author等;但没有任何效果

【问题讨论】:

    标签: python django django-views django-forms django-templates


    【解决方案1】:

    get_context_data 方法中,您有object_list,它是get_queryset 方法的结果。所以你可以覆盖get_queryset 方法。你甚至可以在get_context_dataobject_list 中做同样的事情。示例如下:

    def get_queryset(self):
        return Post.objects.all().annotate(zipcode=F('author'))
    

    然后在你的模板中:

    {% for listing in listings %}
      
      <h3>listing.zipcode</h3>
        
    {% endfor %}
    

    这将返回作者对象的 id,因为它是外键。如果您想要一些其他属性,例如 username,请在注释函数中执行 author__username

    【讨论】:

      猜你喜欢
      • 2015-08-11
      • 2020-11-09
      • 2016-12-25
      • 1970-01-01
      • 1970-01-01
      • 2020-05-25
      • 2018-10-08
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多