[英]Django - Accessing Model Field in class based view
我有這個 model
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)
這個基於 function 的視圖使用 model:
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 %}
有了這個,我將取回 model 的每個實例的author
字段。
如何在變量check_for_zipcode
中獲取實例的作者? 我試過self.author
, self.listings.author
等; 但沒有任何作用
在get_context_data
方法中,您有object_list
,它是get_queryset
方法的結果。 因此,您可以覆蓋get_queryset
方法。 您甚至可以在object_list
的get_context_data
中執行相同的操作。 示例如下:
def get_queryset(self):
return Post.objects.all().annotate(zipcode=F('author'))
然后在您的模板中:
{% for listing in listings %}
<h3>listing.zipcode</h3>
{% endfor %}
這將返回作者 object 的 id,因為它是外鍵。 如果您想要一些其他屬性,例如username
,請在注釋 function 中執行author__username
。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.