Django 管理中的空 ID
我正在尝试在 Django Admin 的产品模型中添加新产品,但由于某些原因,添加后 id 字段总是变为空。
下面是我的代码:
models.py
from django.db import models
class Products(models.Model):
id = models.BigAutoField(primary_key=True) # incremental id
title = models.CharField(max_length=200)
def __str__(self):
return self.title
admin.py
from django.contrib import admin
from import_export.admin import ImportExportModelAdmin
from .models import *
class ProductsAdminConfig(ImportExportModelAdmin):
model = Products
search_fields = ('title',)
list_filter = ('title', )
list_display = ('id', 'title', )
admin.site.register(Products, ProductsAdminConfig)
最初,我使用 SQLAlchemy 创建了数据库表 Products,将 CSV 转换为 Mysql。但是,我也希望能够在 Django Admin 中添加新产品。
我尝试清空 SQL 表、清除迁移文件夹并运行 py manage.py makemigrations 和 py manage.py migrate ,但错误仍然存在。
当我尝试添加新产品时,仍然生成具有 null id 的数据行。
你能给我建议一个解决这个问题的方法吗?谢谢你!
更新
这就是我创建表的方式
import pandas as pd
from sqlalchemy import create_engine
class DfToMySQL:
def __init__(self, db, host, user, passwd, port, charset='utf8'):
self.db = db
self.host = host
self.user = user
self.passwd = passwd
self.port = port
self.charset = charset
def set_dataframe(self, path):
self.path = path
self.df = pd.read_csv(self.path, encoding="utf-8-sig")
def connect(self):
self.engine = create_engine(f'mysql+pymysql://{self.user}:{self.passwd}@{self.host}:{self.port}/{self.db}')
def drop_duplicated_rows(self, cols):
if cols:
self.df = self.df.drop_duplicates(subset=cols) # empty param if drop all duplicates
else:
print('\nPlease specify column(s) with duplicated rows!')
def to_mysql(self, table_name='table_name'):
self.table_name = table_name
self.df.to_sql(name=self.table_name, con=self.engine.connect(), if_exists = 'replace', index=False)
def print_sample_df(self, row=20):
print(self.df.head(row))
def df_from_mysql(self, table_name):
con = self.engine
df = pd.read_sql(f'SELECT * FROM {table_name}', con=con)
return df
def add_index_column(self):
arr = range(1, len(self.df) + 1)
self.df.insert(0, "index", arr, allow_duplicates=False)
self.df['index'] = self.df['index'].apply(str)
def add_id_column(self):
arr = range(1, len(self.df) + 1)
self.df.insert(0, "id", arr, allow_duplicates=False)
self.df['id'] = self.df['id'].apply(str)
def to_xlsx(self):
self.df.to_excel(r'sample.xlsx', encoding="utf-8-sig", index=False, header=True)
def execute_query(self, query=''):
self.query = query
self.con = self.engine.connect()
self.con.execute(query)
if __name__ == '__main__':
db = 'homing_pigeon2'
user = 'root'
passwd = ''
host = 'localhost'
port = 3306
charset='utf8'
csv_path = r"../csv/products.csv"
table_name = 'products'
d = DfToMySQL(db=db, host=host, user=user, passwd=passwd, port=port, charset=charset)
d.set_dataframe(csv_path)
d.print_sample_df()
d.connect()
d.add_id_column()
d.print_sample_df()
d.to_xlsx()
d.to_mysql(table_name=table_name)
结论
我想在产品模型中使用 SQLAlchemy 和 Managed=False 创建数据表时,我可以在 Django Admin 中添加新产品而不出现任何错误的唯一方法是在 admin.py 中使用 ImportExportModelAdmin
I'm trying to add a new product in my Products model in Django Admin, yet for some reasons the id field always become null after adding.
Below is my code:
models.py
from django.db import models
class Products(models.Model):
id = models.BigAutoField(primary_key=True) # incremental id
title = models.CharField(max_length=200)
def __str__(self):
return self.title
admin.py
from django.contrib import admin
from import_export.admin import ImportExportModelAdmin
from .models import *
class ProductsAdminConfig(ImportExportModelAdmin):
model = Products
search_fields = ('title',)
list_filter = ('title', )
list_display = ('id', 'title', )
admin.site.register(Products, ProductsAdminConfig)
Originally I created my database table Products with SQLAlchemy, converting CSV to Mysql. However, I wanted to be able to add a new product inside Django Admin as well.
I have tried emptying my SQL table, clearing my migration folder and run py manage.py makemigrations
and py manage.py migrate
, but the error still persisted.
When I tried adding a new product, the data rows with null ids still got generated.
Could you suggest me a way to solve this? Thank you!
UPDATE
This is how I create my table
import pandas as pd
from sqlalchemy import create_engine
class DfToMySQL:
def __init__(self, db, host, user, passwd, port, charset='utf8'):
self.db = db
self.host = host
self.user = user
self.passwd = passwd
self.port = port
self.charset = charset
def set_dataframe(self, path):
self.path = path
self.df = pd.read_csv(self.path, encoding="utf-8-sig")
def connect(self):
self.engine = create_engine(f'mysql+pymysql://{self.user}:{self.passwd}@{self.host}:{self.port}/{self.db}')
def drop_duplicated_rows(self, cols):
if cols:
self.df = self.df.drop_duplicates(subset=cols) # empty param if drop all duplicates
else:
print('\nPlease specify column(s) with duplicated rows!')
def to_mysql(self, table_name='table_name'):
self.table_name = table_name
self.df.to_sql(name=self.table_name, con=self.engine.connect(), if_exists = 'replace', index=False)
def print_sample_df(self, row=20):
print(self.df.head(row))
def df_from_mysql(self, table_name):
con = self.engine
df = pd.read_sql(f'SELECT * FROM {table_name}', con=con)
return df
def add_index_column(self):
arr = range(1, len(self.df) + 1)
self.df.insert(0, "index", arr, allow_duplicates=False)
self.df['index'] = self.df['index'].apply(str)
def add_id_column(self):
arr = range(1, len(self.df) + 1)
self.df.insert(0, "id", arr, allow_duplicates=False)
self.df['id'] = self.df['id'].apply(str)
def to_xlsx(self):
self.df.to_excel(r'sample.xlsx', encoding="utf-8-sig", index=False, header=True)
def execute_query(self, query=''):
self.query = query
self.con = self.engine.connect()
self.con.execute(query)
if __name__ == '__main__':
db = 'homing_pigeon2'
user = 'root'
passwd = ''
host = 'localhost'
port = 3306
charset='utf8'
csv_path = r"../csv/products.csv"
table_name = 'products'
d = DfToMySQL(db=db, host=host, user=user, passwd=passwd, port=port, charset=charset)
d.set_dataframe(csv_path)
d.print_sample_df()
d.connect()
d.add_id_column()
d.print_sample_df()
d.to_xlsx()
d.to_mysql(table_name=table_name)
CONCLUSION
I guess when creating a datable using SQLAlchemy with managed=False in the Products model, the only way I could add a new product inside Django Admin without any errors is using ImportExportModelAdmin in admin.py
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您创建表的脚本不包含自动增量。
我相信运行脚本后您将需要这样做。它是为 BigAutoField 主键分配 id 字段的数据库。
请参阅 mysql 文档:
https://www.techonthenet.com/mysql/auto_increment.php
我是不确定在现有字段中创建命令以在 mysql 中创建后自动增量。
编辑
请参阅 https://stackoverflow.com/a/2169090/4872140
类似问题:
sqlalchemy:如何添加具有自动增量的表行在mysql中
Your script that creates the table is not including an autoincrement.
I believe you'll need to that after you've run your script. It is the database that assigns the id field for a BigAutoField primary key.
See the mysql documentation at:
https://www.techonthenet.com/mysql/auto_increment.php
I'm not certain of the command to make in existing field to have autoincrement after creation in mysql.
EDIT
See https://stackoverflow.com/a/2169090/4872140
Similar question:
sqlalchemy: how to add a table row with autoincrement in mysql