我正在构建类似StumbleUpon的应用程序,其内容必须按语言和类别进行过滤。我有两个简单的路由,语言和类别,但我想知道是否可以在一个简单的路由器声明中。为了不让我感到困惑,我使用Peewee作为ORM。
以下是我已定义的路线:
@app.route("/<language>")
def languages(language):
links = []
for contenido in models.Post.select().where(models.Post.language**language):
links.append(contenido.content)
iframe = random.choice(links)
return render_template('language.html', iframe=iframe, language=language)
@app.route("/<category>")
def categories(category):
links = []
for contenido in models.Post.select().where(models.Post.category**category):
links.append(contenido.content)
iframe = random.choice(links)
return render_template('category.html', iframe=iframe, category=category)
models.py
class Post(Model):
timestamp = DateTimeField(default=datetime.datetime.now)
user = ForeignKeyField(
rel_model=User,
related_name='posts'
)
language = TextField()
category = TextField()
content = TextField()
class Meta:
database = DATABASE
我要做的是在导航功能中与语言和/或类别建立关系。有可能创造这样的东西吗?我实际上真的失去了试图完成这样的事情。当时我的东西看起来有点像我想做的,这里是片段:
@app.route("/<language>/<category>")
def mixin(language, category):
language_links = []
category_links = []
for contenido in models.Post.select().where(models.Post.language**language):
language_links.append(contenido.content)
for contenido in models.Post.select().where(models.Post.category**category):
category_links.append(contenido.content)
if category_links == []:
iframe = random.choice(language_links)
else:
iframe = random.choice(category_links)
return render_template('language.html', iframe=iframe, language=language, category=category)
答案 0 :(得分:0)
您可以执行此操作来检索具有给定语言和类别的帖子:
@app.route("/<language>/<category>")
def mixin(language, category):
links = []
query = models.Post.select().where(
(models.Post.language ** language) &
(models.Post.category ** category))
for contenido in query:
links.append(contenido.content)
iframe = random.choice(links)
return render_template('language.html', iframe=iframe, language=language, category=category)
要获得具有给定语言或类别的帖子,您可以写:
query = models.Post.select().where(
(models.Post.language ** language) | # note the "pipe" instead of "&"
(models.Post.category ** category))
还有&#34; **&#34;运营商可能效率低下。有没有理由你没有使用&#34; ==&#34;代替?如果您需要能够进行不区分大小写的匹配,则可以执行以下操作:
(fn.LOWER(models.Post.language) == language.lower())