Digamos que tengo los siguientes dos modelos:
class Parent(models.Model): name = models.CharField(max_length=48) class Child(models.Model): name = models.CharField(max_length=48) movement = models.ForeignKey(Parent, related_name='children') Y tengo los siguientes DRF generics.ListAPIView donde quiero poder buscar/ Child en objetos secundarios pero en realidad Parent los objetos principales relacionados:
class ParentSearchByChildNameView(generics.ListAPIView): """ Return a list of parents who have a child with the given name """ serializer_class = ParentSerializer def get_queryset(self): child_name = self.request.query_params.get('name') queryset = Child.objects.all() if child_name is not None: queryset = queryset.filter(name__contains=child_name) matched_parents = Parent.objects.filter(children__in=queryset).distinct() return matched_parents Ahora, esto funciona bien para mí. Si un objeto principal tiene 3 objetos Child que coinciden con el "nombre" Parent query_param , entonces solo Parent un objeto principal, que es lo que quiero:
{ "next": null, "previous": null, "results": [ { "url": "URL to parent", "name": "Parent #1", } ] } Sin embargo, lo que también quiero es indicar los ID de objetos Child coincidentes dentro del resultado. Si puedo ilustrar en JSON lo que quiero:
{ "next": null, "previous": null, "results": [ { "url": "URL to parent", "name": "Parent #1", "matched_child": [1, 3, 7] } ] }¿Es esto algo que puedo hacer con las herramientas integradas, sin tener que acceder a la base de datos de forma costosa y repetida?
Sin hacer uso de una característica específica de la base de datos, puede trabajar con un objeto Prefetch [Django-doc] :
from django.db.models import Prefetch class ParentSearchByChildNameView(generics.ListAPIView): """ Return a list of parents who have a child with the given name """ serializer_class = ParentSerializer def get_queryset(self): child_name = self.request.query_params.get('name') return = Parent.objects.filter( children__name__contains=child_name ).prefetch_related( Prefetch('children', Child.objects.filter(name=child_name), to_attr='matched_children') ).distinct() Para el serializador podemos trabajar con un PrimaryKeyRelatedField [drf-doc] :
class ParentSerializer(serializers.ModelSerializer) matched_children = serializers. PrimaryKeyRelatedField( many=True, read_only=True ) class Meta: model = Parent fields = ['url', 'name', 'matched_children' ]Si trabaja con postgresql , puede trabajar con una expresión ArrayAgg [Django-doc] :
from django.contrib.postgres.aggregates import ArrayAgg class ParentSearchByChildNameView(generics.ListAPIView): """ Return a list of parents who have a child with the given name """ serializer_class = ParentSerializer def get_queryset(self): child_name = self.request.query_params.get('name') return = Parent.objects.filter( children__name__contains=child_name ).annotate( matched_children=ArrayAgg('children__pk') ) En el serializador, por lo tanto, agrega un ListField que enumerará a los niños con:
class ParentSerializer(serializers.ModelSerializer) matched_children = serializers.ListField( child=serializers.IntegerField(), read_only=True ) class Meta: model = Parent fields = ['url', 'name', 'matched_children' ]