Skip to content Skip to sidebar Skip to footer

Skip Saving Row If Slug Already Exists In Postgresql Database - Python

I'm setting up a function in my Django Views that calls an API and save the data into my Postgresql database. Everthing was working fine until I got an IntegrityError slugkey alrea

Solution 1:

get_or_createuses all the given values (except defaults keyword) to find the dups.

Change your code to this

Product.objects.get_or_create(
            title=titlefr,
            slug=slugify(titlefr),
            defaults={
                'destination': destinationfr,
                'description': translation,
                'link': item['canonicalUrl'],
                'image': item['image']['url'],
            }
        )

thus only title and slug will be used for finding possible duplicates. All the other values from defaults will not be used for filtering, but will be used for creation.

Also I suggest you to move slug field initialization into clean_fields()method.

Solution 2:

You will need to check if the slug already exists before saving

defsave(self, *args, **kwargs):     
    ifnot self.id:
        if Product.objects.filter(slug=slugify(self.title)).exists():
            self.slug = slugify("f{self.title}-{Product.objects.filter(slug__startswith=slugify(self.title).count + 1}" )
        else:
            self.slug = slugify(self.title)

        super(Product, self).save(*args, **kwargs)

Post a Comment for "Skip Saving Row If Slug Already Exists In Postgresql Database - Python"