I am familiar with this from searching all over for a solution. The
accepted solution is to create a manager.
from django.db.models.aggregates import Count
>
> from random import randint
>
>
> class PaintingManager(models.Manager):
> def random(self):
> count = self.aggregate(count=Count('id'))['count']
> random_index = randint(0, count - 1)
> return self.all()[random_index]
>
>
If I use this as a template, it might look like this
class PostManager(models.Manager):
def random(self):
count = self.aggregate(count=Count('post_id'))['count']
random_index = randint(0, count - 1)
return self.all()[random_index]
I tried this earlier in the week and I got nothing but errors, so I was not
executing it properly. I think it told me there was no "aggregates".
Anyway, moving forward... If this worked to draw a random post_id, then how
do I get from this model to my DetailView? Remember, currently I am using a
simple class-based view - DetailView - to show blog posts. Would I create
another DetailView using PostManager as the model, then create another
urlpattern?
I really appreciate all of the help with this. It would be nice to get a
consensus on how to approach this.
To m712: Your solution might be simple, but I'm not seeing it because there
is no code. Your suggestion was to create a random_post URL pointing a view
that:
1. does shuffle logic
2. returns a redirect to the proper page, ex. /post/$id (is the $ outdated
in Django 2.0?)
Then you say to make a valid URL using a DetailView. Are you saying to make
a different urlpattern than the random_post URL, or are you talking about
making the random_post URL valid?
Since I'm pretty new to Django, I was confused by your suggestion.
--
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 [email protected].
To post to this group, send email to [email protected].
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/b6bc9e7a-1edb-4abc-ab8c-bbe280fd2f8d%40googlegroups.com.
For more options, visit https://groups.google.com/d/optout.