MD *_*LAM 5 django elasticsearch
我已经针对某些模型(帖子、评论、ReactForComment)创建了一个 django-elasticsearch 文档(PostDocument)。一切正常。但是,更新 ReactForComment 模型后,PostDocument 没有得到更新。我的假设是,我需要努力def get_instances_from_related(self, related_instance):,prepare_field但无法找出方法。
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}'
Run Code Online (Sandbox Code Playgroud)
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
Run Code Online (Sandbox Code Playgroud)
我相信你需要修正你的get_instances_from_related方法。当注释对象被传递时,它返回对象,但它不处理方法ReactForComment中的模型get_instances_from_related。
def get_instances_from_related(self, related_instance):
if isinstance(related_instance, Comment):
return related_instance.post
if isinstance(related_instance, ReactForComment):
# Write some code to return the Post object
Run Code Online (Sandbox Code Playgroud)
PS:我认为评论字段ReactForComment应该是ForeignKey而不是ManyToMany。
| 归档时间: |
|
| 查看次数: |
1083 次 |
| 最近记录: |