I think you can use prefetch related for reducing DB query. When fetching registrations from event, you can use prefetch_related to fetch all registrations at once(so multiple db query is not necessary).
So, for this first you can define the model like this:
class Registrations(models.Model):
user = models.ForeignKey(User...)
event = models.ForeignKey(Event, related_name="registrations",..)
Then, you can define the EventSerializer like this:
class EventSerializer(serializer.ModelSerializer):
registrations = RegistrationSerializer(many=True, read_only=True) # <-- getting all registraions via RegistrationSerializer
is_invited = serializer.SerializerMethodField()
class Meta:
model = Event
fields = "__all__"
def get_is_invited(self, obj):
return obj.registrations.filter(user=self.context.get("request").user).exists() # does not make any DB query
SerializerMethodField has been used here to fetch if user is being invited or not.
Now in the view, when calling the Event queryset, use prefetch_related.
# A minimal example
class SomeView(APIView):
def get(self, request, **kwargs):
qset = Event.objects.prefetch_related('registrations').all()
serializer = EventSerializer(qset, many=True)
return Response(serializer.data)