I'm having trouble saving a form in a Django app. I want to create an model called 'dataset' from another model called 'image', both of which are mptt models.
models
class Image(MPTTModel):
name = models.CharField(max_length=50, unique=True)
parent = TreeForeignKey('self', null=True, blank=True, related_name='children')
def __unicode__(self):
return self.name
class Dataset(MPTTModel):
name = models.CharField(max_length=50, unique=True)
image = TreeForeignKey(Image, null=True, blank=True, unique=True, related_name='image')
def __unicode__(self):
return self.name
class MPTTMeta:
parent_attr = 'image'
When I try to save a Dataset, I get an integrity error:
IntegrityError at /associate/
column image_id is not unique
Request Method: GET
Request URL: http://127.0.0.1:8000/associate/
Django Version: 1.6.2
Exception Type: IntegrityError
Exception Value:
column image_id is not unique
Exception Location: C:\Python27\lib\site-packages\django\db\backends\sqlite3\base.py in execute, line 450
views.py
def index(request):
images = Image.objects.all()
datasets = []
for i in images:
if i.rank() >= 3:
dataset = Dataset(image=i, name=i.name)
dataset.save()
datasets.append(dataset)
return render(request, 'associate/index.html', {'datasets':datasets})
def learn(request):
if request.method == 'POST':
try:
dataset = request.POST.get('dataset', False)
model = Dataset.objects.get(name=dataset)
if model:
print model.name
else:
print "no model"
except Dataset.DoesNotExist:
return render(request, 'associate/index.html')
else:
return render(request, 'associate/learn.html', {'dataset':model})
You have unique=True in your Dataset model for image field. This means you cannot assign one image to different Dataset instances. But you are doing in it in your index. In your index you trying to create a new dataset for every image every time. But if the Dataset with this image already created - you will get this 'column image_id is not unique' error. Please review your application logic and either remove unique=True or rewrite the behavior.