我将sql "view“作为一个虚拟表来学习,以方便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 | sales@villagetoys.com |
| 1000000003 | Fun4All | jjones@fun4all.com |
| 1000000004 | Fun4All | dstephens@fun4all.com |
| 1000000005 | The Toy Store | kim@thetoystore.com |
| 1000000006 | toy land | sam@toyland.com |
+------------+---------------+-----------------------+
5 rows in set (0.014 sec)当我随后查看Django文档时,没有这样的功能来创建可以简化数据操作的虚拟“模型表”。
在使用Django ORM时,我应该忘记虚拟表"view“吗?
发布于 2018-08-13 16:43:37
据我所知,Django目前没有内置的视图支持。
但是您可以通过使用包来构造这样的视图。
安装程序包后(例如,使用pip):
pip install django-database-view此外,必须在settings.py文件中注册dbview应用程序:
# 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的调用应该更改为dbview模块的CreateView。看起来像这样:
from django.db import migrations
from dbview import CreateView
class Migration(migrations.Migration):
dependencies = []
operations = [
CreateView(
name='CustomerEMailList',
fields=[
# ...
],
),
]发布于 2019-11-11 00:44:01
根据Django ORM Cookbook by Agiliq,您可以像下面这样做。
创建视图:
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()我还没有尝试过,但我一定会的。
发布于 2020-12-19 20:24:37
我创建了一个Django插件,你可以用它来创建一个视图表。你可以在pypi.org上通过here查看
使用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 createviewtablehttps://stackoverflow.com/questions/51817841
复制相似问题