Answer the question
In order to leave comments, you need to log in
Django - how to add manytomany data when saving a model?
Good afternoon. Django 4 has a Post model and a DictWords model. There is a ManyToMany relationship between them. The task is that when saving a post, the entire text is divided into separate words and saved to the DictWords dictionary of words with setting up a connection between the post and these words.
The question is - in which direction to dig? Signals - m2m_changed? Thank you.
Answer the question
In order to leave comments, you need to log in
Did something like this:
@receiver(pre_save, sender=Posts)
def my_handler(sender, **kwargs):
instance = kwargs.pop('instance', None)
result_list = []
for w in instance.post.split():
res = ''
for i in w.lower():
if i.isalpha():
res += i
if res and not res in result_list:
result_list.append(res)
for i in result_list:
obj, is_created = DictWords.objects.get_or_create(name=i)
instance.list_words.add(obj)
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question