Create database view from django model

前端 未结 3 1885
故里飘歌
故里飘歌 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:28

    According to the Django ORM Cookbook by Agiliq, you can do it like the following.

    Create view:

    create view temp_user as
    select id, first_name from auth_user;
    

    Create a model which is not managed and naming a db_table explicitly:

    class TempUser(models.Model):
        first_name = models.CharField(max_length=100)
    
        class Meta:
            managed = False
            db_table = "temp_user"
    

    You'll be able to query then, but you'll receive an error once you try to update.

    Query like always:

    TempUser.objects.all().values()
    

    I haven't tried this yet, but I certainly will.

提交回复
热议问题