django raw sql query does not return data

111 views
Skip to first unread message

soumyajit banerjee

unread,
Sep 26, 2018, 8:17:54 AM9/26/18
to django...@googlegroups.com
Hi everyone,

class Post(models.Model):
    author = models.ForeignKey('auth.User',on_delete=models.CASCADE,)
    title = models.CharField(max_length=200)
    text = RichTextField()
    created_date = models.DateTimeField(default=timezone.now)
    published_date = models.DateTimeField(blank=True, null=True)

    def __str__(self):
        return self.title

this is my sample model

and this is my view

def index(request):
    fetch_post_data = Post.objects.filter(published_date__lte=timezone.now()).order_by('-created_date')[:5]
    fetch_pgraph_data = Post.objects.raw("select count(title) as uno,published_date from blog_post group by DATE(published_date)")
    #fetch_pgraph_data = Post.objects.raw("select * from blog_post")
    template_var = {'postodj':fetch_post_data,'userdataobj':fetch_pgraph_data}
    return render(request,'home.html',context=template_var)

when I am trying to fetch the data using fetch_pgraph_data, it's showing Raw query must include the primary key  


--
Soumyajit Banerjee
  
   

Matthew Pava

unread,
Sep 26, 2018, 9:20:10 AM9/26/18
to django...@googlegroups.com

Listen to the error message.  Include the primary key in the queryset.  You can use any field and alias it as “id” if you need to trick the system.

Although, couldn’t that raw query use the ORM in a better way?

Post.objects.annotate(uno=Count(‘title’), published_date_date=Cast(‘published_date’, DateField())).values(‘uno’, ‘published_date_date’)

--
You received this message because you are subscribed to the Google Groups "Django users" group.
To unsubscribe from this group and stop receiving emails from it, send an email to django-users...@googlegroups.com.
To post to this group, send email to django...@googlegroups.com.
Visit this group at https://groups.google.com/group/django-users.
To view this discussion on the web visit https://groups.google.com/d/msgid/django-users/CAG8c6EFsFt_1UwgSch_1mY92x%2BboSrwow7H5umj4-WeYs0f2hg%40mail.gmail.com.
For more options, visit https://groups.google.com/d/optout.

Reply all
Reply to author
Forward
0 new messages