0

I'm introducing django. I've created a model with two fields: Clientes and Equipos.

I wanna print but with my own format, so I would like to have a list or better a dict for it.

But I don't know what "example = models.object.values()" do. I don't know if example is a list, dictionary...

I've tried with models.object.get() but it doesn't work.

thanks.

2 Answers 2

1

Acutally, example is an instance of django.db.models.query.ValuesQuerySet, not just a simple list, it's a queryset

Because of example is a query set, you can use query set method, do whatever you want.The django queryset document is helpful.

you can traverse example variable like this:

for item in example:
  do_what_you_want(item)

As you declare in you model, your example may like this:

example = [  
             {'Clients':'clients data','Equipos':'equipos data'},
             {'Clients':'clients data','Equipos':'equipos data'}
          ]

I don't recommend you to convert your example to list type, if you do this, you can not use the powerfull django query set method.Django queryset method is more powerful than a python native list.

Sign up to request clarification or add additional context in comments.

1 Comment

well, I understand. So if I want to print my django query do_what_you_want should be print item directly.
0
example = models.object.values()

example will be a kind of iterator of dicts where keys are the field names of a model. To make it a list of dicts just do:

example = list(models.object.values())

So example will look something like this:

[
    {'id': 1, 'Clientes': 'some clientes', 'Equipos': 'some equipos'},
    {'id': 2, 'Clientes': 'anoter clientes', 'Equipos': 'another equipos'}
]

4 Comments

I understand, thanks but what happens if I would have more than 2 fields ? I mean... ` example = models.object.values(Clientes,Equipos,AnotherField,AnotherField) ` what is the key in that case? I've another issue. I got it, but when I print it there is an extra char "u" before my key. Look, [(u'test22', 4), (u'test', 4)] and it should be 'test22',4 ...
Of course the additional keys will be added to the dicts. {..., 'AnotherField': 'some'}. And I forgot to mention that the id field will be in the dict too.
Extra u char before the string means that the string is in unicode: docs.python.org/2/howto/…
thanks catavaran, wow! I've just another question... I'm trying to get the values of one Client. I'm doing this: `

Your Answer

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