Issue
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]
messageObj.hash_tags.set(hash_tags)
messageObj.save()
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;
hash_tag
----------
skills
Solution
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
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.