Как сохранить модель django после сохранения поля "многие ко многим" и внешнего ключа

Я работаю над проектом Django, в котором есть несколько полей, включая множество полей ForeignKey и ManyToMany.

и я пытаюсь создать плоский файл json, сериализовав эту модель, чтобы я мог проиндексировать его на сервере эластичного поиска, используя asticsearch-DSL.

models.py

class Video(models.Model):
    """Video model"""

    title = models.CharField(
        max_length=255,
        )
    education_levels = models.ManyToManyField(
        EducationLevel,
        verbose_name=_("Education Level")
    )

    languages = models.ManyToManyField(
        Language,
        verbose_name=_("Languages")
    )

    def save(self, *args, **kwargs):
        # Save the model instance
        super(Video, self).save()
        # After saving model instance, serialize all the fields
        # And save to elastic search
        self.serialize()


    def serialize(self):
        """Method that serialize all the dependencies and call
          elastic search to post data"""

        # The problem I am facing is
        # This method only able to serialize only its fields not able
        # to serialize Foreignkey and ManytoMany field.
        # The problem is

        serialized_data = dict(
            self.title, # got serialized
            # Not able to serialized as the instace is not saved before this model get saved.
            education_levels=[education_level.level for education_level in self.education_levels.all()],
            #   # Not able to serialized as the instace is not saved before this model get saved.
            languages=[language.language for language in self.languages.all()],
            )

        # Save data to Elastic search
        save_to_elastic_server(index="videoindex", data=serialized_data)

        # Q. How to serialize all the many to many fields of a model before instance gets saved.
        # Q. How to access all the many to many fields and foreign key before model get saved.
        # Q. how to save the Django model after its many to many fields get saved

0 ответов

Другие вопросы по тегам