django-import-export: Import foreign keys that do not exist (creating new values in Foreign key)
I am trying to import values which do not already exist my foreign key. I would like import/export to add these new values to the ForeignKey model.
I’ve tried adding “null/blank” to the models, but it still will not create (import) new values in the foreign key. The error I get is “DoesNotExist: x matching query does not exist.”
Here is a sample of my Admin.py (which only imports to a foreign key if the values being imported already exist).
store_name = fields.Field(column_name='store_name', attribute='Store', widget=widgets.ForeignKeyWidget(Store, 'store_name'))
def clean(self, value):
val = super(ForeignKeyWidget, self).clean(value)
object, created = Store.objects.get_or_create(store_name='')
class Meta:
model = Product
fields = ('id', 'second_name', 'product_name', store',)
export_order = ('id', 'second_name', 'product_name')
skip_unchanged = False
report_skipped = False
widgets = {
'published': {'format': '%d.%m.%Y'},
}
Can anyone advise please?
Thanks
About this issue
- Original URL
- State: closed
- Created 9 years ago
- Comments: 19 (6 by maintainers)
I’ve written it this way:
Usage example
def clean(self, value, row=None, *args, **kwargs):https://github.com/django-import-export/django-import-export/commit/8e81b409aae501d1f882f4a4fd458112c2eccac1#diff-948ac927a7e0c8c8d0bb8026e9a49d62L288@int-ua, I used your post as a basis to implement my Many-to-many widget with creation. @patently-offensive, your answer was helpful too.
Many-to-Many Widget with object creation
Usage
In
admin.py:This approach should:
create=Truecreate=FalseThere are some cases where this might not work, for example, if a list of ID’s are passed or if field values are non-string-based.
Does anyone have this working in a many to many context, in particular a model with an m2m relationship with itself?
For example, I have a Product model, with an m2m relationship to itself to represent products that are competitive with each other. Example data:
I need Product C to be created while importing row 1 and related to Product A and Product D to be created with importing row 3 and linked to Product C.
The below will create new values, but will only create an M2M relationship if the foreign key value already exists. In the above example:
Yes, use debugger, insert this in line before one where exception is raised and then inspect variables: