Question

I am trying to build an extra field in a Django query to specify whether an article belongs to a Journal.

I am trying to do something like Article.objects.filter(title__icontains='foo').extra(select={in_the_journal:Function_Belongs_To_Journal(journal_id)})

I am currently iterating the search results to find that out but I'd rather like to retrieve this info from the database already

My models.py are as follows:

class Article(models.Model):
    title               = models.CharField(max_length=400)
    content             = models.TextField()
    date                = models.DateTimeField('date published', null=True, default = timezone.now())


class Journal(models.Model):
    name          = models.CharField(max_length=200)
    authors       = models.ManyToManyField(Author, null=True, blank = True)
    articles      = models.ManyToManyField(Article, null=True, blank = True)

Is that a way to add an extra field to indicate that? Either using extra or annotate Django tags?

Était-ce utile?

La solution 2

I found a great solution to avoid iterating over a list. This way, the Database retrieves the result with an extra column.

Performance is much better now, check it out:

journal_id = 10
query = 'SELECT COUNT(*) FROM data_journal_articles as data WHERE data.journal_id = %s AND data.article_id = data_article.id' % journal_id
articles = Article.objects.filter(
    date__gte = request_data['start_date'], 
    date__lte = request_data['end_date'], 
    ).extra(select={'is_checked': query})

The extra field is a counter of relations between a given journal and a given author. This result could be either one or zero. Depending on it, result will be shown differently in the front-end.

Cheers,

Autres conseils

Just use reverse relationship:

Article.objects.filter(title__icontains='foo', journal__pk=journal_id)

update to comment: if you need all articles and you want to know which of them have journals or not, use RelatedManger:

articles = Article.objects.filter(title__icontains='foo')
for a in articles:
    journals = a.journal_set.all()
    if journals:
        # article have journals
        # list of Journal objects is in journals
    else:
        # article have not journals

Of course you can put this loop in template:

{% for a in articles %}
    {% if a.journal_set.all %}
         color1
    {% else %}
         color2
    {% endif %}
{% endfor %}
Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top