我学习了sql“视图”作为虚拟表,方便SQL操作,比如
MySQL [distributor]> CREATE VIEW CustomerEMailList AS
-> SELECT cust_id, cust_name, cust_email
-> FROM Customers
-> WHERE cust_email IS NOT NULL;
Query OK, 0 rows affected (0.026 sec)
MySQL [distributor]> select * from customeremaillist;
+------------+---------------+-----------------------+
| cust_id | cust_name | cust_email |
+------------+---------------+-----------------------+
| 1000000001 | Village Toys | [email protected] |
| 1000000003 | Fun4All | [email protected] |
| 1000000004 | Fun4All | [email protected] |
| 1000000005 | The Toy Store | [email protected] |
| 1000000006 | toy land | [email protected] |
+------------+---------------+-----------------------+
5 rows in set (0.014 sec)
当我随后检查 Django 文档时,没有这样的功能来创建可以简化数据操作的虚拟“模型表”。
使用 Django ORM 时是否应该忘记虚拟表“视图”?
据我目前所知,Django 没有对视图的内置支持。
django-database-view
包构建这样的视图。
安装软件包后(例如使用 pip):
pip install django-database-view
此外,
dbview
应用程序必须在settings.py
文件中注册:
# settings.py
INSTALLED_APPS = (
# ...
'dbview',
# ...
)
现在你可以构建一个视图,这看起来有点像构建模型,只不过你需要实现一个 view(..)
函数来指定视图背后的查询。类似于:
from django.db import models
from dbview.models import DbView
class CustomerEMailList(DbView):
cust = models.OneToOneField(Customer, primary_key=True)
cust_name = models.CharField()
cust_email = models.CharField()
@classmethod
def view(klass):
qs = (Customers.objects.filter(cust_email__isnull=False)
.values('cust_id', 'cust_name', 'cust_email'))
return str(qs.query)
现在我们可以进行迁移了:
./manage.py makemigrations
现在在迁移中,我们需要进行更改
:与构造视图相关的对migrations.CreateModel
的调用应更改为
CreateView
模块的dbview
。看起来像的东西:from django.db import migrations
from dbview import CreateView
class Migration(migrations.Migration):
dependencies = []
operations = [
CreateView(
name='CustomerEMailList',
fields=[
# ...
],
),
]
create view temp_user as
select id, first_name from auth_user;
创建一个“不受管理”的模型并显式命名 db_table:
class TempUser(models.Model):
first_name = models.CharField(max_length=100)
class Meta:
managed = False
db_table = "temp_user"
然后您就可以查询,但是一旦尝试更新,您就会收到错误。
像往常一样查询:
TempUser.objects.all().values()
我还没有尝试过,但我肯定会尝试。
我创建了一个 Django 插件,您可以在其中创建视图表。您可以在 pypi.org 上查看
这里pip install django-view-table
安装并设置 INSTALLED_APPS
INSTALLED_APPS = [
'viewtable',
]
因此,视图表模型可以写成如下:
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
最后创建表:
python manage.py createviewtable