views:

470

answers:

1

I have inserted a definition for a view in $template_dir/sql/$someTableName.sql file. (create or replace view) so every time I run syncdb, the db views are created.

Can I create in models.py a python class which accesses that view?

Is it better practice to just use python's raw sql functionality instead?

---EDIT---

Another problem I have is that the view doesn't have a primary key, but django seems to be assuming there will be one because I get an error caught an exception while rendering: (1054, "Unknown column 'appName_currentleagues.id' in 'field list'") But I don't have such a member defined:

Class CurrentLeagues(models.Model):
        League = models.ForeignKey(League)
        class Meta:
                managed = False

So my guess is that django reasonably sees that I don't define a primary key in the CurrentLeagues class, so Django assumes there's one called id. Is there a way to tell Django that there is no primary key (since this is actually a view), or is that not even my problem?

+3  A: 

See Unmanaged models

You define the model as usual and add managed = False to the meta options:

class MyModel(models.Model):
    ...
    class Meta:
         managed = False
Will Hardy
But how do I associate that python class with the mysql view I want it associated with? And do I need to explicitly type the members of "MyModel" correctly to match the spelling of the fields in the view and it just works automatically somehow?
Thr4wn
I just need to spell the view as `appName_classname` because that's the spelling that django automatically uses for every python Model instance.
Thr4wn
You can manually pass the name of the view using the `db_table` meta option: http://docs.djangoproject.com/en/dev/ref/models/options/#db-table. Yes you will need to type the field names in, otherwise django wont have a python version of your models. If you want to reduce the amount of typing you could employ an intricate web of abstract models and inheritance, but I would keep things as simple as possible, even if it means a little repetition.
Will Hardy
If you set `primary_key=True` on one of your fields, django wont automatically create the `id` field. It seems you have to have one field as a primary key. If you're using sqlite or oracle, you might get away with this hack: http://groups.google.com/group/django-developers/browse_thread/thread/5611a45dc23f6e06?pli=1
Will Hardy