我正在开发一个Django项目,该项目包含许多字段,包括许多ForeignKey和ManyToMany字段。
我试图通过序列化这个模型来创建一个扁平的json文件,这样我就可以使用elasticsearch-DSL将它索引到弹性搜索服务器中。
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