user76047
user76047

Reputation: 53

Use database view in Django

I saw the question can i use a database view as a model in django and tried it in my app, but that didn't work.

I created a view named "vi\_topics" manually and it had "id" column but I kept getting an error, even if I added "id" field explicitly, saying

"no such column: vi_topics.id"

Here is the definition of my model named Vitopic:

from django.db import models

class Vitopic(models.Model):
    title = models.CharField(max_length=200)
    content = models.TextField()
    author_name = models.CharField(max_length=200)
    author_email = models.CharField(max_length=200)
    view_count = models.IntegerField(default=0)
    replay_count = models.IntegerField(default=0)
    tags = models.CharField(max_length=255)
    created_at = models.DateTimeField(auto_now_add=True)
    updated_at = models.DateTimeField(auto_now=True)

    class Meta:
        db_table = 'vi_topics'

Note: I use sqlite3.

Upvotes: 3

Views: 4732

Answers (2)

WBAR
WBAR

Reputation: 4984

Try this: http://docs.djangoproject.com/en/dev/ref/models/options/#managed

managed

Options.managed

New in Django 1.1: Please, see the release notes

Defaults to True, meaning Django will create the appropriate database tables in syncdb and remove them as part of a reset management command. That is, Django manages the database tables' lifecycles.

If False, no database table creation or deletion operations will be performed for this model. This is useful if the model represents an existing table or a database view that has been created by some other means. This is the only difference when managed is False. All other aspects of model handling are exactly the same as normal. This includes

  1. Adding an automatic primary key field to the model if you don't declare it. To avoid confusion for later code readers, it's recommended to specify all the columns from the database table you are modeling when using unmanaged models.
  2. If a model with managed=False contains a ManyToManyField that points to another unmanaged model, then the intermediate table for the many-to-many join will also not be created. However, a the intermediary table between one managed and one unmanaged model will be created.

    If you need to change this default behavior, create the intermediary table as an explicit model (with managed set as needed) and use the ManyToManyField.through attribute to make the relation use your custom model.

For tests involving models with managed=False, it's up to you to ensure the correct tables are created as part of the test setup.

Upvotes: 3

Acti67
Acti67

Reputation: 607

id = models.IntegerField(primary_key=True)

Upvotes: 2

Related Questions