Django IntegrityError manytomany field


I’m trying to implement hashtags in my django app
I have a message model with a field like this

hash_tags = models.ManyToManyField(HashTag, related_name='message_hash_tags')

And this is the HashTag model

    hash_tag = models.CharField(max_length=140, primary_key=True) 

And I’m setting the hashtags to the message like this

            hash_tags_list = Functions.extract_hashtags(message["message"])
            hash_tags = [HashTag.objects.get_or_create(hash_tag=ht) for ht in hash_tags_list]

But this errors out

django.db.utils.IntegrityError: insert or update on table "messaging_message_hash_tags" violates foreign key constraint "messaging_message_ha_hashtag_id_068959e9_fk_messaging"
DETAIL:  Key (hashtag_id)=((<HashTag: HashTag object (skills)>, True)) is not present in table "messaging_hashtag".

Tho I can find the HashTag object (skills) in my messaging_hashtag table:

SELECT * FROM messaging_hashtag;


get_or_create returns a tuple which contains the object and a flag on whether the object was created or not, so something like: (obj, created)

To fix this, just extract the obj from the tuple. For example using [0] on the result:

hash_tags = [ HashTag.objects.get_or_create(hash_tag=ht)[0] for ht in hash_tags_list ]

Answered By – BrianD

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply

(*) Required, Your email will not be published