我运行以下查询来在 SQLite 数据库中创建数据库视图:
CREATE VIEW customerview AS
SELECT
a.id
, name
, email
, vat
, street
, number
, postal
, city
, country
, geo_lat
, geo_lon
, customer_id
, is_primary
FROM customerbin_address a
, customerbin_customer b
WHERE b.id = a.customer_id
AND a.is_primary = 1
在 models.py 中我添加了模型:
class Customerview(models.Model):
name = models.CharField(max_length=100, db_column='name')
email = models.EmailField(unique=True, db_column='email')
vat = VATNumberField(countries=['NL', 'BE', 'FR', 'DE', 'UK'], blank=True, null=True, db_column='vat')
street = models.CharField(max_length=100, db_column='street')
number = models.IntegerField(null=True, db_column='number')
postal = models.IntegerField(null=True, db_column='postal')
city = models.CharField(max_length=100, db_column='city')
country = CountryField(db_column='country')
is_primary = models.BooleanField(null=False, db_column='is_primary')
geo_lat = models.DecimalField(max_digits=9, decimal_places=6, blank=True, null=True, db_column='geo_lat')
geo_lon = models.DecimalField(max_digits=9, decimal_places=6, blank=True, null=True, db_column='geo_lon')
class Meta:
managed = False
db_table = 'customerview'
在 admin.py 中我更改了列表:
@admin.register(models.Customerview)
class CustomerviewAdmin(admin.ModelAdmin):
list_display = ('name', 'email', 'vat', 'street', 'number', 'postal', 'city', 'country', 'is_primary', 'geo_lat', 'geo_lon')
readonly_fields = ('name', 'email', 'vat', 'street', 'number', 'postal', 'city', 'country', 'is_primary', 'geo_lat', 'geo_lon',)
如何在我的应用程序中以编程方式添加带有上述查询的数据库视图?
Django 的迁移框架可让您执行原始 SQL - https://docs.djangoproject.com/en/3.1/ref/migration-operations/#runsql
因此,您可以创建一个空迁移 (
manage.py makemigrations <appname> --empty
),然后编辑它以通过 migrations.RunSQL()
调用执行视图创建 SQL。
也许你应该尝试使用 get_view_str 方法https://pypi.org/project/django-database-view/#description