A
A
alex_deerk2016-07-30 22:02:05
PostgreSQL
alex_deerk, 2016-07-30 22:02:05

Django/PostgreSQL how to get rid of IntegrityError?

I changed the database backend from SQLite to PostgreSQL, an error appeared:
models.py:

class Phone(Item):
    standards = models.CharField(verbose_name='Стандарты и технологии', max_length=500, blank=True)
    front_camera = models.IntegerField(verbose_name='Размер фронтальной камеры', default=0, blank=True, help_text='Размер камеры в МП')
    front_camera_other = models.CharField(verbose_name='Камера фронтальная дополнительно', max_length=100, blank=True)
    sim_count = models.IntegerField(verbose_name='Количество сим', default=1, blank=True)
    link_category = models.ForeignKey(Category, default=1, editable=False)


class Item(models.Model):
    class Meta:
        abstract = True
        ordering = ["-date"]
    name = models.CharField(max_length=100, verbose_name='Название', help_text='Введите название', default='')
    availability = models.CharField(max_length=100, verbose_name='Наличие', choices=available, default=available[0])
    photo = models.ImageField(verbose_name='Главное фото', upload_to=upload_path, blank=False, help_text='Обязательное поле')
    photo1 = models.ImageField(verbose_name='Фото 1', upload_to=upload_path, blank=True)
    photo2 = models.ImageField(verbose_name='Фото 2', upload_to=upload_path, blank=True)
    photo3 = models.ImageField(verbose_name='Фото 3', upload_to=upload_path, blank=True)
    photo4 = models.ImageField(verbose_name='Фото 4', upload_to=upload_path, blank=True)
    photo5 = models.ImageField(verbose_name='Фото 5', upload_to=upload_path, blank=True)
    video = models.URLField(verbose_name='Видеообзор', blank=True, help_text='Введите адрес YouTube видео')
    description = models.TextField(verbose_name='Описание', max_length=1500, blank=True)
    date = models.DateTimeField(auto_now_add=True, editable=False)
    price = models.DecimalField(verbose_name='Цена в розницу', max_digits=20, decimal_places=2, help_text='Обязательное поле')
    price_opt = models.DecimalField(verbose_name='Цена оптом', max_digits=20, decimal_places=2, default=0, help_text='Если не надо - оставить нулём')

    diagonal = models.DecimalField(verbose_name='Диагональ', default=0, max_digits=20, decimal_places=2, blank=True, help_text='Диагональ в дюймах')
    resolution = models.CharField(verbose_name='Разрешение экрана', max_length=50, blank=True, help_text='Вводить через англискую букву \'x\'')
    display_other = models.CharField(verbose_name='Дисплей дополнительно', max_length=200, blank=True)

    wireless = models.CharField(verbose_name='Беспроводные возможности', max_length=500, blank=True)

    interfaces = models.CharField(verbose_name='Интерфейсы и подключения', max_length=500, blank=True)

    battery = models.IntegerField(verbose_name='Ёмкость батареи', default=0, blank=True, help_text='Ёмкость батареи в mah')

    camera = models.IntegerField(verbose_name='Размер камеры', default=0, blank=True, help_text='Размер камеры в МП')
    camera_other = models.CharField(verbose_name='Камера дополнительно', max_length=100, blank=True)

    osystem = models.CharField(verbose_name='Операционная система', max_length=500, blank=True)
    count_core = models.IntegerField(verbose_name='Количесво ядер', choices=cores, default=cores[0])
    core_other = models.CharField(verbose_name='Процессор', max_length=200, blank=True)
    ram = models.IntegerField(verbose_name='Оперативная память', default=0, blank=True, help_text='Размер в МБ')
    memory = models.IntegerField(verbose_name='Внутреняя память', default=0, blank=True, help_text='Размер в ГБ')
    memory_other = models.CharField(verbose_name='Память дополнительно', max_length=200, blank=True)

    other = models.CharField(verbose_name='Дополнительно', max_length=200, blank=True)
    link_items = models.ForeignKey(Items, default=1, editable=False)
    inv = models.IntegerField(editable=False, default=get_inv, primary_key=True)
    likes = models.IntegerField(editable=False, default=0)

    def __str__(self):
        return self.name

    def get_thumb(self):
        url = self.photo.url
        url = url.split('.')
        thumb_url = url[0] + '_thumb.' + url[1]
        return thumb_url

    def delete(self, *args, **kwargs):
        shares = Share.objects.filter((Q(gen_item__exact=self.inv) | Q(sec_item__exact=self.inv)))
        if shares:
            for share in shares:
                share.delete()
        path = '{0}/{1}/{2}/'.format(MEDIA_ROOT, self.link_category_id, self.name)
        print(path)
        try:
            for file in listdir(path):
                remove(path + file)
            rmdir(path)
        except BaseException:
            pass
        super(Item, self).delete(*args, **kwargs)

    def save(self, *args, **kwargs):
        super(Item, self).save(*args, **kwargs)
        try:
            compress_img(self.photo.path, (250, 250))
            compress_img(self.photo.path, (800, 600))
            photos = [self.photo1, self.photo2,
                      self.photo3, self.photo4,
                      self.photo5]
            for photo in photos:
                if photo != '':
                    compress_img(photo.path, (800, 600))
        except BaseException as e:
            f = open(ERROR_LOG, 'a')
            f.write(e)
            f.close()
        finally:
            pass

    def get_item(self):
        return '/item/' + str(self.inv)

Mistake:
IntegrityError at /adminpanel/new/phone/
insert or update on table "shop_phone" violates foreign key constraint "shop_phone_link_items_id_add95557_fk_shop_items_id"
DETAIL: Key (link_items_id)=(1) is not present in table "shop_items".

Answer the question

In order to leave comments, you need to log in

1 answer(s)
S
sim3x, 2016-07-30
@alex_deerk

ForeignKey
default=1
remove default

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question