Login

Models with database views

Author:
diverman
Posted:
June 13, 2009
Language:
Python
Version:
1.0
Score:
1 (after 3 ratings)

This example shows, how to use database views with django models. NewestArticle models contains 100 newest Articles. Remember, that NewestArticle model is read-only. Tested with mysql.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
class ArticleBase(models.Model):
    title = models.CharField(max_length=32, db_index=True)
    date_time = models.DateTimeField(auto_now=True, db_index=True)
    text = models.TextField()
    authors = models.ManyToManyField('Author')

    class Meta:
        abstract = True
        ordering = ( '-date_time', )

class Article(ArticleBase):
    pass

class NewestArticle(ArticleBase)
    """ READ ONLY MODEL """
    def save(self, **kwargs):
        raise NotImplementedError

DROP TABLE app_newestarticle_authors;
DROP TABLE app_newestarticle;
CRETAE VIEW app_newestarticle AS SELECT * FROM app_article ORDER BY date_time DESC LIMIT 100;
CRETAE VIEW app_newestarticle_authors AS SELECT article_id newestarticle_id, author_id FROM app_article_authors;

More like this

  1. Template tag - list punctuation for a list of items by shapiromatron 9 months ago
  2. JSONRequestMiddleware adds a .json() method to your HttpRequests by cdcarter 9 months, 1 week ago
  3. Serializer factory with Django Rest Framework by julio 1 year, 4 months ago
  4. Image compression before saving the new model / work with JPG, PNG by Schleidens 1 year, 4 months ago
  5. Help text hyperlinks by sa2812 1 year, 5 months ago

Comments

Please login first before commenting.