I've created a django-elasticsearch document(PostDocument) against some models(post, comment, ReactForComment). Everything is working fine. However, after updating ReactForComment model the PostDocument is not getting update.
My assumption is, I need to work on def get_instances_from_related(self, related_instance): or prepare_field but can't figure out the way.
models.py
class Post(models.Model):
STATUS_CHOICES = (
('draft', 'Draft'),
('published', 'Published'),
)
title = models.CharField(max_length=250)
slug = models.SlugField(max_length=250, unique_for_date='publish')
author = models.ForeignKey(User, on_delete=models.CASCADE, related_name='blog_posts')
body = models.TextField()
publish = models.DateTimeField(default=timezone.now)
created = models.DateTimeField(auto_now_add=True)
updated = models.DateTimeField(auto_now=True)
status = models.CharField(max_length=10, choices=STATUS_CHOICES, default='draft')
tags = TaggableManager()
def __str__(self):
return self.title
class Comment(models.Model):
post = models.ForeignKey(Post, on_delete=models.CASCADE, related_name='post_comments')
name = models.CharField(max_length=80)
body = models.TextField()
email = models.EmailField()
created = models.DateTimeField(auto_now_add=True)
updated = models.DateTimeField(auto_now=True)
active = models.BooleanField(default=True)
class Meta:
ordering = ['created']
def __str__(self):
return f'Comment by {self.name} on {self.post}'
class ReactForComment(models.Model):
comment = models.ManyToManyField(Comment, on_delete=models.CASCADE, related_name='react_comments')
like = models.IntegerField(null=True, blank=True)
happy = models.IntegerField(null=True, blank=True)
sad = models.IntegerField(null=True, blank=True)
neutral = models.IntegerField(null=True, blank=True)
def __str__(self):
return f'React on {self.comment}'
Document.py
@registry.register_document
class PostDocument(Document):
post_comments = fields.NestedField(properties={
'id': fields.IntegerField(),
'react_comments': fields.NestedField(properties={
'id': fields.IntegerField(),
'like': fields.IntegerField(),
'happy': fields.IntegerField(),
'sad': fields.IntegerField(),
'neutral': fields.IntegerField()
})
})
class Index:
name = 'post'
settings = {'number_of_shards': 1,
'number_of_replicas': 1}
class Django:
model = Post
fields = [
'id',
'title',
'author',
'body',
]
related_models = [Comment, ReactForComment]
def get_instances_from_related(self, related_instance):
if isinstance(related_instance, Comment):
return related_instance.post