Django import-export new values in foriegn key model

被刻印的时光 ゝ 提交于 2020-01-24 09:53:45

问题


I'm using the django import-export library to data. It works well except I cannot get it to import objects which don't already exist in the foreign key.

If the objects (values in the csv) exist in the foreign key model- then it imports fine.

But if the objects/values don't exist in the foreign key model- it says "matching query does not exist" and will not import the data.

How can I tell it to add new object to the foreign key model if they don't exist in the foreign key?

Models.py snippet

class Store(models.Model):

    store_name = models.CharField(max_length=30)
    def __unicode__(self):
        return self.store_name
    #etc

class Product(models.Model):

    Store = models.ForeignKey(Store)
    Category = models.ForeignKey(Category)
    first_name = models.CharField(max_length=30)
    second_name = models.CharField(max_length=30)
...

Admin.py snippet

admin.site.register(Category)
admin.site.register(Store)

class ProductResource(resources.ModelResource):

     store_name = fields.Field(column_name='store_name', attribute='Store',
                       widget=ForeignKeyWidget(Store, 'store_name'))

    def __unicode__(self):
        return self.store_name.name

    class Meta:
        model = Product
        fields = ('id', 'first_name', 'second_name','store_name')
        export_order = ('id', 'second_name', 'first_name')
        skip_unchanged = False
        report_skipped = False
        widgets = {
                'published': {'format': '%d.%m.%Y'},
                }


class ProductAdmin(ImportExportModelAdmin):
    resource_class = ProductResource
    list_display = ('first_name', 'second_name')

admin.site.register(Product, ProductAdmin)

回答1:


In ForeignKeyWidget you have method

  def clean(self, value):
        val = super(ForeignKeyWidget, self).clean(value)
        return self.model.objects.get(**{self.field: val}) if val else None

you could try to override it to do something like get_or_create...

it should look something like this...

from import_export.widgets import ForeignKeyWidget
class MyCustomizationToFKWidget(ForeignKeyWidget):

      def clean(self, value):
            val = super(ForeignKeyWidget, self).clean(value)
            HERE SOME LOGIC OVERRIDEN



回答2:


Provided the ForeignKey of your model can be null :

MyForeignKeyName = Models.ForeignKey(<modelclass>,blank=True, null=True)

You can add a before_import_row() method in your Resource class :

def before_import_row(self,row) :
    fieldname = 'MyForeignKeyName'
    if not( <modelclass>.objects.filter(pk=row[fieldname]).exists() ) :
        # print(row['id'],row[fieldname],'unknown key !') # console log
        row[fieldname ] = None # or something else.. *

*.. compliant with your foreignkey configuration [ python None = SQL null ]

I'm a bit new to Django so maybe it's not the better way, but this solves my problem.

There's also something about db_constraint=False that can be added to ForeignKey's arguments (some info @stackoverflow and @django) but well, I did not find my way with it.



来源:https://stackoverflow.com/questions/32369984/django-import-export-new-values-in-foriegn-key-model

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