Create database view from django model

前端 未结 3 1879
故里飘歌
故里飘歌 2021-02-04 09:29

I learned sql \"view\" as a virtual table to facilitate the SQL operations, like

MySQL [distributor]> CREATE VIEW CustomerEMailList AS
    -> SELECT cust_         


        
3条回答
  •  一整个雨季
    2021-02-04 10:32

    I created a Django plugin which you can create a view table. You can check it here, on pypi.org

    Install with pip install django-view-table and set INSTALLED_APPS like this:

    INSTALLED_APPS = [
        'viewtable',
    ]
    

    And so, a view table model can be written as follows:

    from django.db import models
    from view_table.models import ViewTable
    
    # Base table
    class Book(models.Model):
        name = models.CharField(max_length=100)
        category = models.CharField(max_length=100)
    
    
    # View table
    class Books(ViewTable):
        category = models.CharField(max_length=100)
        count = models.IntegerField()
    
        @classmethod
        def get_query(self):
            # Select sql statement
            return Book.objects.values('category').annotate(count=models.Count('category')).query
    

    Finally, create the table:

    python manage.py createviewtable
    

提交回复
热议问题