8

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?

2 Answers 2

6

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
Sign up to request clarification or add additional context in comments.

4 Comments

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?
I just need to spell the view as appName_classname because that's the spelling that django automatically uses for every python Model instance.
You can manually pass the name of the view using the db_table meta option: 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.
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: groups.google.com/group/django-developers/browse_thread/thread/…
3

Try to use python manage.py inspectdb or python manage.py inspectdb > models.py

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.