Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django MVC pattern for non database driven models?

Tags:

I'm just working my way through Django, and really liking it so far, but I have an issue and I'm not sure what the typical way to solve it.

Suppose I have a View which is supposed to be updated when some complex Python object is updated, but this object is not driven by the database, say it is driven by AJAX calls or directly by the user or something.

Where does this code go? Should it still go in models.py????

like image 495
DevDevDev Avatar asked Aug 17 '09 22:08

DevDevDev


1 Answers

Your models.py can be (and sometimes is) empty. You are not obligated to have a model which maps to a database.

You should still have a models.py file, to make Django's admin happy. The models.py file name is important, and it's easier to have an empty file than to try and change the file expected by various admin commands.

The "model" -- in general -- does not have to map to a database. The "model" -- as a general component of MVC design -- can be anything.

You can -- and often do -- define your own "model" module that your views use. Just don't call it models.py because it will confuse Django admin. Call it something meaningful to your application: foo.py. This foo.py manipulates the real things that underpin your application -- not necessarily a Django Model.model subclass.

Django MVC does not require a database mapping. It does explicitly expect that the module named models.py has a database mapping in it. So, use an empty models.py if you have no actual database mapping.

Your views.py can use

import foo  def index( request ):     objects = foo.somelistofobjects()     *etc.* 

Django allows you to easily work with no database mapping. Your model can easily be anything. Just don't call it models.py.


Edit.

Are Views registered with Models? No.

On update to the Model by the Controller the Views get notified? No.

Is the Model strictly the data respresentation as this is really MVP? Yes.

Read the Django docs. It's simple.

Web Request -> URL mapping -> View function -> Template -> Response.

The model can be used by the view function. The model can be a database mapping, or it can be any other thing.

like image 140
S.Lott Avatar answered Sep 22 '22 00:09

S.Lott