Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

How to query actions by a target object property #428

Open
sanfilippopablo opened this issue Mar 25, 2019 · 2 comments
Open

How to query actions by a target object property #428

sanfilippopablo opened this issue Mar 25, 2019 · 2 comments
Labels
question general questions, not really an issue

Comments

@sanfilippopablo
Copy link

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?

@auvipy auvipy added the question general questions, not really an issue label Mar 30, 2019
@valentijnscholten
Copy link

@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
Copy link

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

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
question general questions, not really an issue
Projects
None yet
Development

No branches or pull requests

3 participants