tags:

views:

55

answers:

2

Hi, I have just started to work on a django project( and learn django at the same time) and I came across some design questions that I can't really answer with my limited knowledge so I decided to ask it here. anyway Here is the questions: 1) where would you put raw queries. is it ok to put row queries in view.py files? My personal opinion is to put them only in models.py files. 2) where can you query db? can you call query methods in models.py, views.py, templates? I think they should be in models.py or views.py but not in templates. specifically calls like "MyModel__attribute_set__all" should not be used in templates.

Since I am new in django (and python) I am not really sure if I have the right idea about this. I appreciate for any feedback.

+1  A: 

Sounds like you're on a good path already.

I try to:

  • Keep my views slim, in terms of code, and my models fat
  • keep my templates even slimmer and free of database lookups; if I have to do something that hits the DB that for some reason isn't viable to do in the view, I do it via a templatetag or filter so that it can improved and/or cached, and is also easy to find, and is as DRY as a can be
  • define and execute any raw SQL in the models that use it
stevejalim
A: 

where would you put raw queries. is it ok to put row queries in view.py files?

Queries are most commonly seen in the view.py; yes it's ok there.

My personal opinion is to put them only in models.py files.

If you're using the same query a lot then create a "manager" for the model. You'll put the very commonly used querys there. "Only" in there would be making life hard for yourself.

where can you query db?

Usually in views.py; not uncommonly in models.py.

can you call query methods in ... templates?

Technically it is possible but, logically, very strongly discouraged.

I think they should be in models.py or views.py but not in templates

I agree.

John Mee
I am not convinced about first one. I think we should never use raw queries in views and here is why: Raw queries are special cases that we query db without control of django framework. For instance, if we want to change our database implementation, those queries must be checked if they are compatible with the new backend. Also, since they run directly on db we might need to add extra exception handling in our code. if those queries are separate from our django code we can easily do those validations without effecting rest of the code. Than again,they might be ok if there is just a few of them
yilmazhuseyin
I gladly agree. My apologies for misunderstanding. You use the word "raw" then "row" so I got confused. I have never found cause to use "raw" - I didn't even know it existed (New with 1.2). I don't use it, and I think the circumstances would have to be pretty extreme to justify it, but obviously someone has found the need. Nice to know it's there, I'd probably fall back to using "Q" before resorting to raw.
John Mee