flice com
flice com

Reputation: 125

django get_or_create throws Integrity Error

I have read this thread: get_or_create throws Integrity Error

But still not fully understand when get_or_create returns False or IntegrityError.

I have the following code:

django_username = 'me'
user = get_user_model().objects.filter(username=django_username).first()

action_history, action_added = ActionModel.objects.get_or_create(
                date=date_obj,  # date object 
                account_name=unique_name,  # e.g. account1234
                target=follower_obj, # another model in django
                user=user,  # connected django user
                defaults={'identifier': history['user_id']}
            )

While the model looks like:

class ActionModel(models.Model):
    """
    A model to store action history.

    """

    identifier = models.BigIntegerField(
        _("identifier"), null=True, blank=True) # target id
    account_name = models.CharField(_("AccountName"), max_length=150, null=True, blank=True)  # account name of the client
    date = models.DateField(_("Date"), auto_now=False, auto_now_add=False)  # action date
    target = models.ForeignKey(Follower, verbose_name=_("Target"), on_delete=models.CASCADE)  # username of the done-on action
    user = models.ForeignKey(
        settings.AUTH_USER_MODEL,
        on_delete=models.CASCADE,
        null=True,
        editable=False,
        db_index=True,
    )  # django user that performed the action

    class Meta:
        verbose_name = _("Action")
        verbose_name_plural = _("Actions")
        unique_together = [
            ['account_name','date','target'],
        ]

Sometimes it return IntegrityError, and sometimes (when unique constrain exists it will return False on created).

Upvotes: 0

Views: 666

Answers (2)

flice com
flice com

Reputation: 125

OK. I figured it out, I sent:

account_name = 'adi'
date = '07-02-21'
target = 'nana1'
user = 'me'

While it was not exist with the specific user = 'me' but with user = None:

account_name = 'adi'
date = '07-02-21'
target = 'nana1'
user = None

So the get was failing and the created try to duplicate the unique_together = ['account_name','date','target'].

Upvotes: 0

Shamsiddin Parpiev
Shamsiddin Parpiev

Reputation: 99

You have unique_together constraint. Lets imagine you have object in db with following data account_name='bob', date='2020-12-12', target='b', user='12'

In you get_or_create method you are doing this

ActionModel.objects.get_or_create(
            date='2020-12-12', 
            account_name='bob',  
            target='b', 
            user="13"
        )

you providing exactly this three parameters with this data, but user this time is 13, so django could not find any object and it tries to create one, but with this parametres you cant create object because there is unique constraint

Upvotes: 1

Related Questions