NilCoalescing / djangochannelsrestframework

A Rest-framework for websockets using Django channels-v4

Home Page:https://djangochannelsrestframework.readthedocs.io/en/latest/

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

observer for instances based on foregien key

AGM-90 opened this issue · comments

Can we write a observer for instances based on foregien key

I think this is asking for something I had a question about as well.

For example, if we have the following Models:

from django.db import models


class Reporter(models.Model):
    first_name = models.CharField(max_length=30)
    last_name = models.CharField(max_length=30)
    email = models.EmailField()


class Article(models.Model):
    headline = models.CharField(max_length=100)
    pub_date = models.DateField()
    reporter = models.ForeignKey(Reporter, on_delete=models.CASCADE)

Can an Observer listen for "all Articles changed/updated/deleted for Reporter X"?

Yes you will need to create a custom observer for this.

In this blog post there is a custom subscription for a hashtag.

If you created a ArticleConsumer and defined a @model_observer method with @{..}.groups_for_signal and @{...}.groups_for_consumer that group the articles by reported id and let users subscribe based on reporter id respectively.

you will also need to create a custom subscribe_to_reporter action that captures the id of the reporter you want to subscribe to and calls the subscribe method on the observer.

I know the syntax for this is all rather obscure and hard to figure out. I have attempted a few differnt passes at trying to create a more declarative aporach that would be easier to work with but due to the limitations of how django events work and channels so as to avoid loads of extra db lookups I think what is there right now is the best solution.