如何解决在django-import-export中使用ForeignKeywidget返回的MultipleObjects [英] How to solve MultipleObjectsReturned with ForeignKeywidget in django-import-export

查看:52
本文介绍了如何解决在django-import-export中使用ForeignKeywidget返回的MultipleObjects的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个资源可以帮助我将数据导入到我的模型中,但是它不起作用.我尝试了所有可能的选择,但没有成功.这就是资源.

I have a resource that should help me import data into my model but it doesn't work. I have tried all the options I could but to no success. This is the resource.

class ImportStudentsResource(resources.ModelResource):
    klass = fields.Field(attribute = 'class',column_name='class',widget= ForeignKeyWidget(Klass,'name'))
    stream = fields.Field(attribute = 'stream',column_name='stream',widget=ForeignKeyWidget(Stream,'name'))
    gender = fields.Field(attribute = 'gender',column_name='gender', widget=ForeignKeyWidget(Gender, 'name'))
    school = fields.Field(attribute = 'school',column_name='school', widget=ForeignKeyWidget(School, 'name'))
    class Meta:
        model = Students
        fields = ('school','adm','name','kcpe','klass','stream','gender','notes')
        import_id_fields = ('adm',)
        import_order = ('school','adm','name','kcpe','klass','stream','gender','notes')

这是通过资源导入模型的数据

This is the data to import into the model through the resource

这是回溯.

Traceback (most recent call last):
  File "D:\Python\Django\Links Online Exams\env\lib\site-packages\django\core\handlers\exception.py", line 47, in inner
    response = get_response(request)
  File "D:\Python\Django\Links Online Exams\env\lib\site-packages\django\core\handlers\base.py", line 181, in _get_response
    response = wrapped_callback(request, *callback_args, **callback_kwargs)
  File "D:\Python\Django\Links Online Exams\env\lib\site-packages\django\views\generic\base.py", line 70, in view
    return self.dispatch(request, *args, **kwargs)
  File "D:\Python\Django\Links Online Exams\env\lib\site-packages\django\views\generic\base.py", line 98, in dispatch
    return handler(request, *args, **kwargs)
  File "D:\Python\Django\Links Online Exams\Links_Online_Results\students\views.py", line 52, in post
    result = resource.import_data(data_set, dry_run=True, collect_failed_rows=True, raise_errors=True)
  File "D:\Python\Django\Links Online Exams\env\lib\site-packages\import_export\resources.py", line 741, in import_data
    return self.import_data_inner(dataset, dry_run, raise_errors, using_transactions, collect_failed_rows, **kwargs)
  File "D:\Python\Django\Links Online Exams\env\lib\site-packages\import_export\resources.py", line 788, in import_data_inner
    raise row_result.errors[-1].error
  File "D:\Python\Django\Links Online Exams\env\lib\site-packages\import_export\resources.py", line 658, in import_row
    self.import_obj(instance, row, dry_run)
  File "D:\Python\Django\Links Online Exams\env\lib\site-packages\import_export\resources.py", line 512, in import_obj
    self.import_field(field, obj, data)
  File "D:\Python\Django\Links Online Exams\env\lib\site-packages\import_export\resources.py", line 495, in import_field
    field.save(obj, data, is_m2m)
  File "D:\Python\Django\Links Online Exams\env\lib\site-packages\import_export\fields.py", line 110, in save
    cleaned = self.clean(data)
  File "D:\Python\Django\Links Online Exams\env\lib\site-packages\import_export\fields.py", line 66, in clean
    value = self.widget.clean(value, row=data)
  File "D:\Python\Django\Links Online Exams\env\lib\site-packages\import_export\widgets.py", line 396, in clean
    return self.get_queryset(value, row, *args, **kwargs).get(**{self.field: val})
  File "D:\Python\Django\Links Online Exams\env\lib\site-packages\django\db\models\query.py", line 433, in get
    raise self.model.MultipleObjectsReturned(
students.models.Klass.MultipleObjectsReturned: get() returned more than one Klass -- it returned 2!

无值的可能原因

class StudentsForm(forms.ModelForm):
    class Meta:
        model = Students
        fields = ("school","name","adm",'klass',"stream","kcpe","gender","notes")
        widgets = {
            'school':forms.TextInput(attrs={"class":'form-control','value':'','id':'identifier','type':'hidden'}),
            'name':forms.TextInput(attrs={"class":'form-control'}),
        }

    def __init__(self, school, *args, **kwargs):
        super(StudentsForm, self).__init__(*args, **kwargs)
        self.fields['klass'] = forms.ModelChoiceField(
            queryset=Klass.objects.filter(school=school),label='Class')
        self.fields['stream'].queryset = Stream.objects.none()
        if 'klass' in self.data:
            try:
                klass = int(self.data.get('klass'))
                self.fields['stream'].queryset = Stream.objects.filter(klass_id=klass).order_by('name')
            except (ValueError, TypeError):
                pass  # invalid input from the client; ignore and fallback to empty City queryset
        elif self.instance.pk:
            self.fields['stream'].queryset = self.instance.klass.stream_set.order_by('name')

推荐答案

您违反了类别(行)(以及流)行的 ForeignKey 约束

You are violating the ForeignKey constraint with class (klass) (and also stream) row

Jaq / class 2
Lucy / class 2
# only 1 can have 2 as its a ForeignKey
# same error will happen in stream row 4 Eagle 2 Hawk

您应该使用 ManyToMany 字段来填充 Foreignkey

You should insted of Foreignkey use a ManyToMany field

文档: https://docs.djangoproject.com/zh/3.2/ref/models/fields/#manytomanyfield

这篇关于如何解决在django-import-export中使用ForeignKeywidget返回的MultipleObjects的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆