Given that I have a django model that has a ForeignKey that is linked to itself.
class DjangoModel():
[...]
successor = models.ForeignKey('self', null=True)
I was able to write a custom django database function like this:
from django.db.models import BooleanField
from django.db.models import Func
class IsNull(Func):
"""
"""
template = '%(expressions)s IS NULL'
def __init__(self, *args, **kwargs):
kwargs['output_field'] = BooleanField()
super(IsNull, self).__init__(*args, **kwargs)
So I can do this:
queryset = DjangoModel.objects.all()
queryset = queryset.annotate(**{'is_latest': IsNull('successor')})
and if use `queryset.values()` .. I get
[{'pk': 1, is_latest': True}, {'pk': 2, 'is_latest': False}, ]
where `is_latest == True` when `successor` field is NULL for an object.
Now I want to do something similar, but have no idea where to start!
The bundled `django.contrib.auth.models.User` has a ManyToMany relations to `django.contrib.auth.models.Group` model
For my project, there are multiple user group types, e.g customer / marketing / finance etc
What I want to do.. is annotate a `User` queryset with `is_FOO` field where `FOO` is a group name. e.g `is_customer` or `is_marketing`
So if I use `.values()` on a queryset, I should get something like this:
[{'pk': 1, 'is_customer': True, 'is_marketing': False }, {'pk': 1, 'is_customer': True, 'is_marketing': True }]
The group name could be hardcoded, e.g
queryset.annotate(**{'is_customer': IsGroupMember('customer')})
I just need help with the `IsGroupMember` database function!
Is that even possible? Any hints or tips to get me started?
Any help will be genuinely appreciated. Many Thanks