1

Consider the following Django model:

class SomeModel(models.Model):
    some_var = models.IntergerField()

Whats the best way to get an array of a models parameters from a search results?

Example (not working of course):

a = SomeModel.objects.all().some_var

would give something like [3, 4, 1, 9, 1, 2]

2 Answers 2

5

There is existing queryset method called values_list https://docs.djangoproject.com/en/1.10/ref/models/querysets/#values-list

a = SomeModel.objects.all().values_list('some_var', flat=True)

We are using flat=True so that it will give flat list

Entry.objects.values_list('id').order_by('id')
[(1,), (2,), (3,), ...]
Entry.objects.values_list('id', flat=True).order_by('id')
[1, 2, 3, ...]
Sign up to request clarification or add additional context in comments.

6 Comments

That's correct,So the upvote.Wondering, What will be the structure of result?? Comma separated list maybe..??
@PrakharTrivedi: Yes, a list (which are comma separated ;) ) of values in some_var column
@PrakharTrivedi strictly speaking, the result won't be a list, it would be a queryset. If all you want to do is to iterate over it or pass as a value to some other queryset.filter(), it will behave just the same. But if you want to concatenate it to some other list, use negative indexing (like qs[-2]), you would have to explicitly convert it to a list.
@PrakharTrivedi Actually it will be QueryList not QuerySet.
@SardorbekImomaliev I can't find anything named QueryList in Django (1.8.13) code. And calling type(qs.values_list()) yields ValuesListQuerySet. So, while it is not a simple QuerySet, it is a subclass.
|
0

You can yield the list, this would like the following:

foo = [i.some_var for i in SomeModel.objects.all()]

But I've been notified that this would waste the memory.

1 Comment

List comprehension yields a list, not a generator. And if SomeModel has many fields, this would be wasteful in terms of RAM, since Django would have to load everything into memory.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.