问题
I am using django-import-export library and I am trying to implement ForeignKey widget which is available to lookup related objects using Author.name instead of Author.pk. Now, the here is the tricky part for the given calendar year I only have one author with the same name, however, next year the author name will be similar. When i try to import, of course, it brings the issue saying that more than Author.name was found.
Is there a suggestion to solve the issue?
回答1:
I've used before_save_instance() to do something similar to this. Here's some pseudo-code for how this might work:
class MyModelResource(ModelResource):
# Specify fields and Meta information here
def before_save_instance(self, instance, using_transactions, dry_run):
# Replace the below with your actual code
year = instance.year
author = Author.objects.filter(year=year)
instance.author = author
return instance
This assumes that the information you need to get the correct author is available in the row you're importing.
来源:https://stackoverflow.com/questions/55434001/foreign-key-widget-finds-more-than-1-value-how-should-i-approach-this