justquick / django-activity-stream

Generate generic activity streams from the actions on your site. Users can follow any actors' activities for personalized streams.
http://django-activity-stream.rtfd.io/en/latest/
BSD 3-Clause "New" or "Revised" License
2.36k stars 484 forks source link

How to query actions by a target object property #428

Open sanfilippopablo opened 5 years ago

sanfilippopablo commented 5 years ago

I tried to search for a similar issue but found nothing. Sorry if it's a duplicate.

I want to query actions by a target object property. Let's say I have:

class MyModel(models.Model):
    color = models.CharField(max_length=256, default="red")

and that models is the target of many actions. Now I want to get a feed of all the actions for this target in which the color is "blue". My first idea was to do:

my_model_ct = ContentType.objects.get_for_model(MyModel)
actions = Action.objects.filter(target_content_type=my_model_ct, target__color="blue")

but turns out you can't do that with GFKs.

My next idea was to do this:

my_model_ct = ContentType.objects.get_for_model(MyModel)
ids = MyModel.objects.filter(color="blue").annotate(str_id=Cast('id', CharField(max_length=10))).values_list('str_id', flat=True)
actions = Action.objects.filter(target_content_type=my_model_ct, target_object_id__in=ids)

That yielded the expected result. It's also efficient, given that it will make everything in just one DB query. But is there a better (or official) way of doing this?

valentijnscholten commented 3 years ago

@sanfilippopablo Did you ever find a better / more elegant (/ faster?) way of doing this? Just noticed your (this) issue, similar to the one I just created.

valentijnscholten commented 3 years ago

@sanfilippopablo actually just answered my own question / issue :-D