【发布时间】:2020-03-23 01:26:47
【问题描述】:
我想按学校和类别这两个不同的类别过滤帖子。
models.py
class Category(models.Model):
name = models.CharField(max_length=100)
slug = models.SlugField(max_length=100, unique=True)
class Meta:
ordering = ('name',)
verbose_name = 'category'
verbose_name_plural = 'categories'
def __str__(self):
return self.name
class School(models.Model):
name = models.CharField(max_length=100)
slug = models.SlugField(max_length=100, unique=True)
class Meta:
ordering = ('name',)
verbose_name = 'school'
verbose_name_plural = 'schools'
def __str__(self):
return self.name
class VideoPost(models.Model):
category = models.ForeignKey('Category', on_delete=models.CASCADE)
school = models.ForeignKey('School', on_delete=models.CASCADE)
title = models.CharField(max_length=100)
slug = models.SlugField(max_length=100, unique = True)
author = models.ForeignKey(User, on_delete=models.CASCADE)
video = models.CharField(max_length=100, blank=True)
content = RichTextUploadingField()
image = models.ImageField(upload_to='images', null=True, blank=True)
date_posted = models.DateTimeField(default=timezone.now)
def _get_unique_slug(self, *args, **kwargs):
self.slug = slugify(self.title)
super(VideoPost, self).save(*args, **kwargs)
def __unicode__(self):
return self.title
School 和 Category 是 VideoPost 的外键。因此,在 db 中它只有它的 id,而不是 slug 或名称。是category_id & school_id
views.py
def post_list(request):
school = request.GET.get('school', None)
category = request.GET.get('category', None)
posts = VideoPost.objects.all()
if school:
posts.filter(school=school).order_by('-date_posted')
elif category:
posts.filter(category=category).order_by('-date_posted')
elif school & category:
posts.filter(school=school).filter(category=category).order_by('-date_posted')
else:
posts.order_by('-date_posted')
## I wanted to filter them in multiple ways where the posts are filtered by either one of the category, or both, but It doesn't work.
## The only way I found that's working is:
posts = VideoPost.objects.all().filter(school=school).filter(category=category)
##This way, it filtered the posts with its school and category id specified.
return render(request, 'stories/browse.html', {'posts': posts})
模板.html
<a href="{% url 'post_list' %}?school=1&category=4">Link</a>
所以,我的问题是
是否可以在数据库中为外键提供文本?这样该 url 可以更具可读性,并且我可以在 url 标签中使用文本。 喜欢
<a href="{%url 'post_list' %}?school=MIT&category=sports">Link</a>如何正确使用带有 IF 语句的 request.GET.get() 方法?
【问题讨论】: