How to solve MultipleObjectsReturned with ForeignKeywidget in django-import-export
Asked Answered
F

1

0

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

enter image description here

This is the Traceback.

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!

Possible cause of the None values

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')
Fairtrade answered 11/4, 2021 at 19:46 Comment(0)
S
2

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

You should insted of Foreignkey use a ManyToMany field

documentation: https://docs.djangoproject.com/en/3.2/ref/models/fields/#manytomanyfield

Scurrility answered 11/4, 2021 at 20:15 Comment(6)
Thank you for your effort in answering. the fields actually import now but with None values in both klass and stream... with klass__name = fields.Field(widget= ManyToManyWidget(Klass, field = 'name')) stream__name = fields.Field(widget=ManyToManyWidget(Stream, field = 'name'))Fairtrade
See my comment and give a clue, please. @ScurrilityFairtrade
No idea why you are getting None as return. Why are you even using ManyToMany relations do you have the other modules set-up or are those just text fields?Scurrility
if this is the same issue, please can you remove your previous questionBolick
I think the form details I've added has been causing all these but now I don't know how to edit the form to eliminate the error. @ScurrilityFairtrade
I think the form details I've added has been causing all these but now I don't know how to edit the form to eliminate the error. @Matthew HegartyFairtrade

© 2022 - 2024 — McMap. All rights reserved.