使用django-import-export get_or_create()时,“唯一约束失败”

时间:2018-08-03 10:22:10

标签: django django-admin django-import-export

我有三种模式,艺术家,场地和活动。事件模型链接到艺术家和地点。当使用django-import-export导入事件数据时,我希望能够使用Artist或Venue名称而不是主键进行添加。

到目前为止,只有在尚未创建导入模型的情况下,我才设法使它生效。

我的代码如下:

admin.py

from django.contrib import admin
from django import forms
from .models import Venue, Artist, Event
from import_export.admin import ImportExportModelAdmin
from import_export import fields, resources
from import_export.widgets import ForeignKeyWidget

class ArtistForeignKeyWidget(ForeignKeyWidget):
	def clean(self, value,row=None,*args, **kwargs):
            #this takes the value of the input and passes it to 'get_or_create' 
    		artist, created = Artist.objects.get_or_create(artist_name=value)

            #if the artist already exist
            #this returns a UNIQUE constraint error, needs fixing
    		if created == False:
    			return artist

            #if the artist has been created (works fine)
    		else:
    			return artist

class VenueForeignKeyWidget(ForeignKeyWidget):
	def clean(self, value,row=None,*args, **kwargs):
		venue, created = Venue.objects.get_or_create(venue_name=value)
		if created == False:
			return venue
		else:
			#return new venue element
			return venue

class EventResource(resources.ModelResource):
	#create ForeignKeyWidget to replace Artist & VEnue primary key with name in import/export
	artist = fields.Field(column_name='artist', attribute='artist', widget=ArtistForeignKeyWidget(Artist, 'artist_name'))
	venue = fields.Field(column_name='venue', attribute='venue', widget=VenueForeignKeyWidget(Venue, 'venue_name'))
	class Meta:
		model = Event
		exclude = ('user', 'updated')
		fields = (
			'id',
			'date',
			'time',
			'event_code',
			'system',
			'CAM',
			'age_restrictions',
			'entry_restrictions',
		)

class ArtistAdmin(ImportExportModelAdmin):
	actions = None
	list_display = ["artist_name", "genre"]
	list_filter = ["genre"]
	search_fields = ["artist_name", "genre"]

class EventAdmin(ImportExportModelAdmin):
	actions = None
	resource_class = EventResource
	list_display = ["date", "artist", "venue", "event_code", "CAM"]
	list_filter = ["date", "CAM"]
	search_fields = ["date", "artist__artist_name", "venue__venue_name", "event_code", "CAM", "system"]

class VenueAdmin(ImportExportModelAdmin):
	actions = None
	list_display = ["venue_name", "venue_city", "address", "loa", "system_venue"]
	list_filter = ["venue_city", "loa", "system_venue"]
	search_fields = ["venue_name", "venue_city"]



admin.site.register(Venue, VenueAdmin)
admin.site.register(Artist, ArtistAdmin)
admin.site.register(Event, EventAdmin)

我无法理解为什么返回已经创建的艺术家会返回UNIQUE约束错误,而不是仅仅接受已经创建的对象。谁能帮忙解释一下,以便我更正我的代码?

0 个答案:

没有答案