Python 使用Django和Algolia搜索模型索引的持久化数据

Python 使用Django和Algolia搜索模型索引的持久化数据,python,django,algolia,django-1.11,Python,Django,Algolia,Django 1.11,对于Django+Algolia来说,这是一个奇怪的问题。我正在使用特定于Algolia的Django包: $ pip install algoliasearch-django 我有以下模型模式: import os import datetime from channels import Group from django.db import models from django.conf import settings from django.utils.six import pyth

对于Django+Algolia来说,这是一个奇怪的问题。我正在使用特定于Algolia的Django包:

$ pip install algoliasearch-django
我有以下模型模式:

import os
import datetime

from channels import Group

from django.db import models
from django.conf import settings
from django.utils.six import python_2_unicode_compatible
from django.utils.translation import ugettext_lazy as _
from django.core.files.storage import FileSystemStorage
from django.contrib.humanize.templatetags.humanize import naturaltime

BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
SITE_UPLOAD_LOC = FileSystemStorage(location=os.path.join(BASE_DIR, 'uploads/site'))
USER_UPLOAD_LOC = FileSystemStorage(location=os.path.join(BASE_DIR, 'uploads/user'))

@python_2_unicode_compatible
class Room(models.Model):
    """
    This model class sets up the room that people can chat within - much like a forum topic.
    """
    title = models.CharField(max_length=255)
    staff = models.BooleanField(default=False)
    slug = models.SlugField(max_length=250, default='')
    banner = models.ImageField(storage=USER_UPLOAD_LOC, null=True, blank=True)

    def last_activity(self):
        """
        For date and time values show how many seconds, minutes, or hours ago a message
        was sent (i.e., persised to the database) compared to current timestamp return representing string.
        """
        last_persisted_message = Messages.objects.filter(where=self.slug).order_by('-sent_at').first()
        if last_persisted_message is not None:
            # First we can store "last persisted message" time in ISO format (could be useful for sitemap.xml generation; SEO tasks etc)
            last_persisted_message_iso = last_persisted_message.sent_at.isoformat()
            # Use the natural time package form contrib.humanize to convert our datetime to a string.
            last_persisted_message = naturaltime(last_persisted_message.sent_at)
            return last_persisted_message
        else:
            return "No activity to report"
其索引为:

from algoliasearch_django import AlgoliaIndex

class RoomIndex(AlgoliaIndex):
    fields = ('title', 'last_activity')

    settings = {
        'searchableAttributes': ['title'],
        'attributesForFaceting': ['title', 'last_activity'],
        'hitsPerPage': 15,
    }

    index_name = 'Room Index'
基本上,要将“last_activity”值带到前端,它需要通过索引,该索引在运行时会进行更新:

$ python manage.py algolia_reindex
但是,最后一个活动来自上一次(转换为人化的django naturaltime,例如“3天前”等)在websocket连接中发送消息-保存到数据库。除了需要运行algolia_reindex命令才能更新之外,所有这些功能都可以正常工作


不确定如何才能同时完成这项工作…?

好的,所以这项工作在我使用WebSocket时稍微复杂一些。当消息被发送并持久化到数据库时,我们还可以在相关的“consumer”方法中执行以下操作(实际上,consumers.py是views.py文件的websocket等价物,所以我应该知道这一点!)

以下代码行起作用:

client = algoliasearch.Client(settings.ALGOLIA['APPLICATION_ID'], settings.ALGOLIA['API_KEY'])
index = client.init_index('Room Index')
res = index.partial_update_objects([{"last_activity": naturaltime(datetime.datetime.now()), "objectID": your_object_id]}])
对于任何收听者来说,诀窍是根据从客户端传递给消费者的消息值来指定your_object_id

不要忘记添加:

import datetime
from django.conf import settings
from django.contrib.humanize.templatetags.humanize import naturaltime
在consumers.py文件的顶部

我还发现Algolia中特定于python的增量更新文档非常有用: 我


为了以“实时”的方式呈现更新后的时间,我使用了jQuery,但Vue.js或React.js也同样有效。

嘿,感谢您的后续关注!请毫不犹豫地将您的问题发布到