Reputation: 22489
I have a problem in displaying specific columns in my model in django... I have read in the documentation in about the queryset feature of django. my question is that it is also possible in django to run just like this query?
select name, age, address from person;
can anyone can give me an idea, i also try it like this
Mymodel.objects.get(name, age, address)
but there are error in the parameter of name, age and address...
thanks...
Upvotes: 1
Views: 8323
Reputation: 31951
If you want only some columns use only
:
Mymodel.objects.only('name', 'age', 'address')
If you don't want some columns use defer
:
Mymodel.objects.defer('some_big_field')
You can still access field you haven't queried, but it will cost you one mode DB hit.
Also you can use values
and values_list
methods, but instead of model instances they return list of dicts and list of lists respectively.
Upvotes: 10
Reputation: 28637
there are a few different ways. django normally wraps the data in model instances, which is part of the point of the orm. you deal with objects and django deals with the database. so
for person in MyMydel.objects.all():
do_something_with(person.name)
having said that, if you only want certain attributes, e.g. for performance, you can use values
MyMode.objects.values('name', 'age', 'address')
which returns a list of dicts with those values
Upvotes: 5