The following contains a syntax error:
date = datetime.now()-timedelta(minutes=30)
articles = Article.objects.filter(published=True).extra(select = {
"views" : """
SELECT COUNT(*)
FROM myapp_readership
JOIN myapp_article on myapp_readership.which_article_id = myapp_article.id
WHERE myapp_readership.reader_id = myapp_user.id
AND myapp_readership.what_time > %s """ % date,
}).order_by("-views")
The error being: syntax error at or near "01" (where "01" was the datetime object inside extra). It's not much to go on. Can someone point out what's going on?
Background: The models relating to the above code are:
class Article(models.Model):
author = models.ForeignKey(User)
published = models.BooleanField(default=False)
class Readership(models.Model):
reader = models.ForeignKey(User)
which_article = models.ForeignKey(Article)
what_time = models.DateTimeField(auto_now_add=True)
I wrote the above code because I was trying to get all published articles, sorted by unique readership each article experienced in the last 30 mins. I.e. counting how many distinct (unique) views each published article got in the last half an hour, and then producing a list of articles sorted by these distinct views. My code is missing handling the 'distinct' part of the requirement - I don't know how to accomplish that here.
%sin quotes (so that ismyapp_readership.what_time > '%s'). If that helps, consider some other way of building queries - string formatting is the worst (practical) one