Python Django-在基于类的视图中访问模型字段
我有这个型号Python Django-在基于类的视图中访问模型字段,python,django,django-views,django-forms,django-templates,Python,Django,Django Views,Django Forms,Django Templates,我有这个型号 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 = m
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中访问作者”
{%用于清单%中的清单]
作者
{%endfor%}
这样,我将为该模型的每个实例返回author
字段
如何在变量
check\u for_zipcode
中获取实例的作者?我尝试了self.author
,self.listings.author
,等等;但是在get\u context\u data
方法中没有任何东西起作用。您有对象列表
,它是get\u queryset
方法的结果。因此您可以覆盖他使用了get\u queryset
方法。您甚至可以在object\u列表中的get\u context\u data
中执行相同的操作。示例如下:
def get_queryset(self):
return Post.objects.all().annotate(zipcode=F('author'))
然后在模板中:
{% for listing in listings %}
<h3>listing.zipcode</h3>
{% endfor %}
{%用于在清单%]中列出
listing.zipcode
{%endfor%}
这将返回author对象的id,因为它是一个外键。如果您需要一些其他属性,如username
,请在annotate函数中执行author\uu username
{% for listing in listings %}
<h3>listing.zipcode</h3>
{% endfor %}