Anonymous
Django update_or_create получает «повторяющееся значение ключа нарушает ограничение уникальности»
Сообщение
Anonymous » 29 окт 2024, 17:42
Возможно, я неправильно понимаю цель метода модели update_or_create в Django.
Вот моя модель:
Код: Выделить всё
from django.db import models
import datetime
from vc.models import Cluster
class Vmt(models.Model):
added = models.DateField(default=datetime.date.today, blank=True, null=True)
creation_time = models.TextField(blank=True, null=True)
current_pm_active = models.TextField(blank=True, null=True)
current_pm_total = models.TextField(blank=True, null=True)
... more simple fields ...
cluster = models.ForeignKey(Cluster, null=True)
class Meta:
unique_together = (("cluster", "added"),)
Вот мой тест:
Код: Выделить всё
from django.test import TestCase
from .models import *
from vc.models import Cluster
from django.db import transaction
# Create your tests here.
class VmtModelTests(TestCase):
def test_insert_into_VmtModel(self):
count = Vmt.objects.count()
self.assertEqual(count, 0)
# create a Cluster
c = Cluster.objects.create(name='test-cluster')
Vmt.objects.create(
cluster=c,
creation_time='test creaetion time',
current_pm_active=5,
current_pm_total=5,
... more simple fields ...
)
count = Vmt.objects.count()
self.assertEqual(count, 1)
self.assertEqual('5', c.vmt_set.all()[0].current_pm_active)
# let's test that we cannot add that same record again
try:
with transaction.atomic():
Vmt.objects.create(
cluster=c,
creation_time='test creaetion time',
current_pm_active=5,
current_pm_total=5,
... more simple fields ...
)
self.fail(msg="Should violated integrity constraint!")
except Exception as ex:
template = "An exception of type {0} occurred. Arguments:\n{1!r}"
message = template.format(type(ex).__name__, ex.args)
self.assertEqual("An exception of type IntegrityError occurred.", message[:45])
Vmt.objects.update_or_create(
cluster=c,
creation_time='test creaetion time',
# notice we are updating current_pm_active to 6
current_pm_active=6,
current_pm_total=5,
... more simple fields ...
)
count = Vmt.objects.count()
self.assertEqual(count, 1)
При последнем вызове update_or_create я получаю следующую ошибку:
Код: Выделить всё
IntegrityError: duplicate key value violates unique constraint "vmt_vmt_cluster_id_added_c2052322_uniq"
DETAIL: Key (cluster_id, added)=(1, 2018-06-18) already exists.
Почему модель не обновилась? Почему Django попытался создать новую запись, нарушающую ограничение уникальности?
Подробнее здесь:
https://stackoverflow.com/questions/509 ... constraint
1730212924
Anonymous
Возможно, я неправильно понимаю цель метода модели update_or_create в Django. Вот моя модель: [code]from django.db import models import datetime from vc.models import Cluster class Vmt(models.Model): added = models.DateField(default=datetime.date.today, blank=True, null=True) creation_time = models.TextField(blank=True, null=True) current_pm_active = models.TextField(blank=True, null=True) current_pm_total = models.TextField(blank=True, null=True) ... more simple fields ... cluster = models.ForeignKey(Cluster, null=True) class Meta: unique_together = (("cluster", "added"),) [/code] Вот мой тест: [code]from django.test import TestCase from .models import * from vc.models import Cluster from django.db import transaction # Create your tests here. class VmtModelTests(TestCase): def test_insert_into_VmtModel(self): count = Vmt.objects.count() self.assertEqual(count, 0) # create a Cluster c = Cluster.objects.create(name='test-cluster') Vmt.objects.create( cluster=c, creation_time='test creaetion time', current_pm_active=5, current_pm_total=5, ... more simple fields ... ) count = Vmt.objects.count() self.assertEqual(count, 1) self.assertEqual('5', c.vmt_set.all()[0].current_pm_active) # let's test that we cannot add that same record again try: with transaction.atomic(): Vmt.objects.create( cluster=c, creation_time='test creaetion time', current_pm_active=5, current_pm_total=5, ... more simple fields ... ) self.fail(msg="Should violated integrity constraint!") except Exception as ex: template = "An exception of type {0} occurred. Arguments:\n{1!r}" message = template.format(type(ex).__name__, ex.args) self.assertEqual("An exception of type IntegrityError occurred.", message[:45]) Vmt.objects.update_or_create( cluster=c, creation_time='test creaetion time', # notice we are updating current_pm_active to 6 current_pm_active=6, current_pm_total=5, ... more simple fields ... ) count = Vmt.objects.count() self.assertEqual(count, 1) [/code] При последнем вызове update_or_create я получаю следующую ошибку: [code]IntegrityError: duplicate key value violates unique constraint "vmt_vmt_cluster_id_added_c2052322_uniq" DETAIL: Key (cluster_id, added)=(1, 2018-06-18) already exists. [/code] Почему модель не обновилась? Почему Django попытался создать новую запись, нарушающую ограничение уникальности? Подробнее здесь: [url]https://stackoverflow.com/questions/50915911/django-update-or-create-gets-duplicate-key-value-violates-unique-constraint[/url]