Reputation: 2335
I come from an PHP/SQL background, so the whole data access technique in django is a challenge to get my head around. So far in the djangobook, it has taught me to use a unicode function in models.py if i want to get a value from a database.
def __unicode__(self):
return self.name
Surely this is not how its meant to be done? Firstly, it only returns one column, and also if i wanted to access the table from some other function for another purpose, is the "name" column the only thing i can ever return? Its as if i can only ever return one column from the table - in this case i have chosen "name". currently i am doing:
Publisher.objects.filter(name='test')
but here there is no way of altering what i want to be returned, its always down to the static unicode function back in models.py that has to be manually altered? Surely there is a way of just running a python version query looking like
"SELECT name, firstname FROM users WHERE user_id = 1"
so basically, how would i write this query in python without having to use the stupid, limited unicode function? How would a production web app do it? Am i completely missing the concept here?
Thanks, and sorry for the badly explained question.
P.S would it be better to just use SQL in django? or is this bad practice?
Upvotes: 0
Views: 81
Reputation: 55207
Fields can simply be accessed using attribute access:
publisher = Publisher.objects.get(name='test')
print publisher.pk
print publisher.name
print publisher.some_other_field
Or, regarding your example
user = User.objects.get(pk=1)
print user.first_name
print user.last_name
And, in a template:
{{ user.first_name }}
The __unicode__
method is used to display a representation of an object. It is not used for generic field access.
Regarding your question, no, you shouldn't be using SQL here.
Upvotes: 4