0

I am working on a Django project, which has a number of fields including many ForeignKey and ManyToMany Fields.

and I am trying to create a flat json file by serializing this model so that I can index it into an elastic search server by using elasticsearch-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
Community
  • 1
  • 1
shining
  • 1,049
  • 16
  • 31
  • 1
    Would [haystack](http://django-haystack.readthedocs.io/en/master/) solve your problem? – YKL Oct 10 '17 at 06:22
  • I am not using haystack because I need to use some token explicitly in elastic search fields – shining Oct 10 '17 at 06:22
  • you can use signals in django to fulfil this – Amrit Oct 10 '17 at 06:43
  • @amrit Same problem with the signals, as When the model get's saved its related field haven't got saved. So I need some way to save the Model first, and save its related model and serialize the data and its related field and dispatch to ES server. – shining Oct 10 '17 at 06:46
  • Perhaps you could use the Django-specific ``m2m_changed`` signal (https://docs.djangoproject.com/en/3.1/ref/signals/#m2m-changed) to trigger the desired action. – tombreit Jan 06 '21 at 21:54

0 Answers0