Saurabh
Saurabh

Reputation: 23

Django: Shuffle a queryset randomly and access object fields

i have a list

[<Upload: 33-bb6f5d9a98604450>, <Upload: 35-bb6f5d9a98604450>, <Upload: 30-bb6f5d9a98604450>, <Upload: 31-bb6f5d9a98604450>, <Upload: 34-bb6f5d9a98604450>]

which has been generated by

ques = list(sorted(Upload.objects.filter(unique_id=tdetail), key=lambda x: random.random()))

<Upload: 33-bb6f5d9a98604450>

here Upload is the model and 33-bb6f5d9a98604450 is the slug of model upload how can we extract Upload model values from this list

heres my views

def platform(request,e,slug):
article = get_object_or_404(Article,e=e)
tdetail=get_object_or_404(test_detail,test_id=article)
if Platform.objects.filter(user=request.user,test_key=article).exists():
    platform=get_object_or_404(Platform,user=request.user,test_key=article)
    slugs = platform.list
    for obj in slugs:
        ques = Upload.objects.filter(slug=obj.slugs)

     #Upload.objects.filter(slug=slugs)
else:
    ques = list(sorted(Upload.objects.filter(unique_id=tdetail), key=lambda x: random.random()))

    platform=Platform()


    platform.user=request.user
    platform.test_key=article
    platform.list=ques
    platform.save()


return render(request, 'articles/platform.html',{'ques':ques})

here is my model of platform

class Platform(models.Model):
user=models.ForeignKey(User)
test_key=models.ForeignKey(Article)
list=models.CharField(max_length=2000)

def __unicode__(self):
    return u"%s(%s)" % (self.user,self.id_apply)

class Meta:
    unique_together = ('user', 'test_key',)

Upvotes: 0

Views: 2965

Answers (2)

rajkris
rajkris

Reputation: 1793

Try this:

for obj in ques:
    print obj.slug_field

Can access the object fields by iterating through the list generated. I can see that you are trying to shuffle the queryset randomly. Maybe you can do this:

ques = Upload.objects.filter(unique_id=tdetail).order_by('?')

which in turn will be a queryset and you can use it as usual. Or maybe you can use shuffle from random, and do it using python:

Assuming ques is a list:

from random import shuffle
    shuffle(ques)

For the error, Instead of this:

slugs = platform.list

do this:

import json
slugs = json.loads(platform.list)

which will return a list of slugs, after that instead of the loop:

 ques = Upload.objects.filter(slug__in=slugs)

Upvotes: 2

Vivek
Vivek

Reputation: 341

You have to loop through your list. Eg

for upload in ques:
    print upload.field_name

field_name is a column(field) from upload model.

Upvotes: 0

Related Questions