Foreign key widget finds more than 1 value, how should i approach this

南笙酒味 提交于 2019-12-08 03:56:44

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!