Django: how to build relations and queries the best way? -
i'm new django, , i'm having difficulties related objects. easy in terms of sql seems quite tricky here.
i have simple db looks this:
from django.contrib.contenttypes.fields import genericforeignkey, genericrelation django.contrib.contenttypes.models import contenttype django.db import models class language(models.model): code = models.charfield(max_length = 2) name = models.charfield(max_length = 20) class translation(models.model): content_type = models.foreignkey(contenttype) object_id = models.positiveintegerfield() content_object = genericforeignkey('content_type', 'object_id') language = models.foreignkey(language) title = models.textfield() text = models.textfield() class article(models.model): pub_date = models.datetimefield(verbose_name = "publication date") visible = models.booleanfield(default = false) translations = genericrelation(translation)
this follow-up my previous question. andrea corbellini, above model looks clear , simple.
now want show articles on web page. there current language, , need select articles 1) visible , 2) have translation current language. in sql mean joining several tables , filtering them in single query.
how in django? question includes 2 questions: how create fast query , how pass result template.
what first filtering visible , ordering pub_date, iterating through query set, picking articles have proper translation, , copying fields context because template engine doesn't seem understand how access related objects. here code; looks awkward:
articles = article.objects.filter(visible = true).order_by('-pub_date') recent_news = [] article in articles: content = article.content(translation.get_language()) if not content.exists(): go on content = content[0] recent_news.append({ 'pub_date': article.pub_date, 'title': content.title, 'abstract': content.text, 'text': content.text }) context = { 'recent_news_list': recent_news }
what help here 'meta model' or middleware of job , cache result requesting articles language require single query. way?
since info need send template in translation model, query on model, , send template. thing need in article model visible
field, can filter on that:
article = contenttype.objects.get_for_model(article) article_ids = article.objects.filter(visible=true).values_list('id') translations = translation.objects.filter(content_type=article, object_id__in=article_ids) context = {'recent_news_list: translations}
this 3 queries: 1 contenttype (although cached automatically), 1 translations, , 1 articles (and django may indeed 3rd subquery of second).
it's going complicated though; that's cost pay using generic relations. know other question have multiple types related translation, if can away without doing things indeed much simpler.
django django-models