NilCoalescing / djangochannelsrestframework

A Rest-framework for websockets using Django channels-v4
https://djangochannelsrestframework.readthedocs.io/en/latest/
MIT License
613 stars 86 forks source link

observer for instances based on foregien key #165

Closed AGM-90 closed 1 year ago

AGM-90 commented 1 year ago

Can we write a observer for instances based on foregien key

johnthagen commented 1 year ago

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"?

hishnash commented 1 year ago

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.