Django 使用外键模型在基于类的视图中显示额外的内容



我正在尝试向 Django 添加额外的内容 基于类的视图到模板中

我有一些这样的模型

class District(models.Model):
district = models.CharField(max_length=255, null=False, unique=False, blank=True)
def __str__(self):
return self.district

class Street(models.Model):
street_name = models.CharField(max_length=255, null=False, unique=False, blank=True)
district = models.ForeignKey(District, verbose_name=_('district'), on_delete=models.CASCADE, null=True, blank=True)
zone = models.IntegerField(blank=True, null=True)
def __str__(self):
return self.street_name

class Article(models.Model):
user = models.ForeignKey(settings.AUTH_USER_MODEL, null=True, blank=True, related_name="author", on_delete=models.SET_NULL)
timestamp = models.DateTimeField(auto_now_add=True)   
status = models.CharField(max_length=1, choices=STATUS, default=CREATED)
comment = models.CharField(max_length=255, null=True, unique=False, blank=True)
name = models.CharField(max_length=255, null=True, unique=False)
street = models.ForeignKey(Street, verbose_name=_('street'), on_delete=models.CASCADE, null=True, blank=True)

class ArticlesListView(LoginRequiredMixin, PermissionRequiredMixin,ListView):
model = Article
paginate_by = 50
context_object_name = "articles"
permission_required = 'is_staff'
def get_context_data(self, *args, **kwargs):
context = super().get_context_data(*args, **kwargs)
context['Filter_name'] = Article.objects.order_by().values('name').distinct()
context['Filter_user'] = Article.objects.order_by().values('user').distinct()
return context

def get_queryset(self, **kwargs):
return Article.objects.all()

并在模板的后期

{% for f in Filter_name %}
<ul>
<li>{{f.name}}</li>
</ul>
{% endfor %}

如何使用外键在模板中显示地区名称列表和作者姓名列表?

你可以尝试这样的东西

{% for item in model_1.foreign_model_set.all %}
<h1>{{ item }}</h1>
{% endfor %}

相关内容

  • 没有找到相关文章

最新更新