gpt4 book ai didi

python - Django导入/导出: ForeignKey fields return None

转载 作者:行者123 更新时间:2023-12-01 02:46:42 26 4
gpt4 key购买 nike

使用 Django Import/Export,我在将外键字段导入到 Django 模型中时遇到问题。具体来说,我的模型中有三个字段需要导入(第四个字段是参与者,具有默认值,因此我们可以忽略该字段),其中一个是 IntegerField,另外两个是 ForeignKey 字段。

在导入之前,所有三个字段都会转换为数字格式。但是, ForeignKey 字段无法读取这些值,而是导入 NaN (大概是因为我已将这些模型字段设置为 null=True

我针对类似问题尝试了多种解决方案,但都没有解决这个问题。

我在这里做错了什么?

模型.py

class User(auth.models.User,auth.models.PermissionsMixin):
def __str__(self):
return "@{}".format(self.username)

class Forskningsresultater(models.Model):
id = models.IntegerField(primary_key=True)
authors = models.ManyToManyField(settings.AUTH_USER_MODEL, through='PersonRes', blank=True,related_name='authors',verbose_name="Authors")
... (plus irrelevant fields for this question)

class PersonRes(models.Model):
id = models.IntegerField(primary_key=True)
user = models.ForeignKey(settings.AUTH_USER_MODEL,on_delete=models.CASCADE,null=True,verbose_name="user")
forskningsresultater = models.ForeignKey(Forskningsresultater,on_delete=models.CASCADE, null=True,verbose_name="forskningsresultater")
participant = models.BooleanField(default=True)
def __str__(self):
return "{}. Result {}: {}".format(self.id,self.forskningsresultater, self.user)

admin.py

from import_export import widgets, fields, resources
class PersonResResource(resources.ModelResource):
user = fields.Field(column_name='user_id', attribute='user', widget=widgets.ForeignKeyWidget(settings.AUTH_USER_MODEL, 'id'))
forskningsresultater = fields.Field(column_name='forskningsresultater_id', attribute='forskningsresultater', widget=widgets.ForeignKeyWidget(Forskningsresultater, 'id'))
class Meta:
model = PersonRes
fields = ('id','user','forskningsresultater','participant',)

from import_export.admin import ImportExportModelAdmin
class PersonResAdmin(ImportExportModelAdmin):
class Meta:
resource_class: PersonResResource
admin.site.register(PersonRes,PersonResAdmin)

myscript.py

...

df_persres[['A']] = df_persres[['A']].apply(pd.to_numeric)
df_persres[['B']] = df_persres[['B']].apply(pd.to_numeric)
df_persres[['C']] = df_persres[['C']].apply(pd.to_numeric)

df_persres.columns =['id','user_id','forskningsresultater_id']

if( len(df_persres.index) != 0):
import tablib
from import_export import resources
from accounts.models import PersonRes
personres_resource = resources.modelresource_factory(model=PersonRes)()
antall = len(df_persres.index)
for row in range(antall):
dataset = tablib.Dataset([ df_persres.iat[row,0],
df_persres.iat[row,1],
df_persres.iat[row,2]],
headers=['id', 'user_id', 'forskningsresultater_id'])
result = personres_resource.import_data(dataset, dry_run=True)
else:
pass

打印 dataset 时,我得到以下信息(仅显示 dataset 的一个实例):

id       |user_id|forskningsresultater_id
---------|-------|-----------------------
148097456|1480974|56

但是,当我使用 pd.DataFrame.from_records(PersonRes.objects.all().values()) 打印模型时,我得到:

      forskningsresultater_id           id  participant  user_id
0 NaN 338884 True NaN
1 NaN 566233 True NaN
2 NaN 636223 True NaN

3 NaN 754756 True NaN
4 NaN 802856 True NaN
5 NaN 1005256 True NaN
...

最佳答案

列名称应如下所示(删除 _id):

user = fields.Field(column_name='user', attribute='user', widget=widgets.ForeignKeyWidget(settings.AUTH_USER_MODEL, 'id'))
forskningsresultater = fields.Field(column_name='forskningsresultater', attribute='forskningsresultater', widget=widgets.ForeignKeyWidget(Forskningsresultater, 'id'))

关于python - Django导入/导出: ForeignKey fields return None,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45190768/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com