M
M
mspuz2022-01-05 14:29:03
Django
mspuz, 2022-01-05 14:29:03

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

1 answer(s)
M
mspuz, 2022-01-05
@mspuz

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 question

Ask a Question

731 491 924 answers to any question