Как получить отношения один-ко-многим в одной таблице?

Я использую django и rest api. И у меня есть две модели:

class Category(models.Model):
    name = models.CharField(max_length=100)
    slug = models.SlugField(max_length=100)   
    images = models.ImageField(upload_to="photos/categories")
    category = models.ForeignKey("Category", on_delete=models.CASCADE, related_name='part_of', blank=True, null=True)
    date_create = models.DateTimeField(auto_now_add=True)
    date_update = models.DateTimeField(auto_now=True)
    description = models.TextField(max_length=1000, blank=True)
    legislation = models.TextField(max_length=1000, blank=True)
    review = models.TextField(max_length=   000, blank=True)
    eaza  = models.TextField(max_length=1000, blank=True)

    class Meta:
        verbose_name = "category"
        verbose_name_plural = "categories"

    def __str__(self):
        return self.name


class Animal(models.Model):
    name = models.CharField(max_length=100)
    slug = models.SlugField(max_length=100)  
    images = models.ImageField(upload_to="photos/categories")
    category = models.ForeignKey(Category, on_delete=models.CASCADE, related_name='animals')
    date_create = models.DateTimeField(auto_now_add=True)
    date_update = models.DateTimeField(auto_now=True)
    description = models.TextField(max_length=1000, blank=True)
    legislation = models.TextField(max_length=1000, blank=True)
    review = models.TextField(max_length=1000, blank=True)
    eaza  = models.TextField(max_length=1000, blank=True)

    class Meta:
        verbose_name = "animal"
        verbose_name_plural = "animals"

    def __str__(self):
        return self.name

А мой сериализатор выглядит так:

class AnimalSerializer(serializers.ModelSerializer):
    class Meta:
        model = Animal
        fields = ['id','name', 'description']


class CategorySerializer(serializers.ModelSerializer):
    animals = AnimalSerializer(many=True)
    
    class Meta:
        model = Category
        fields = ['id','category_id','name', 'description', 'animals']

и views.py:

class CategoryViewSet(viewsets.ModelViewSet):
    serializer_class = CategorySerializer
    queryset = Category.objects.all() 
    
    @action(methods=['get'], detail=False)
    def mainGroups(self,request):        
        mainGroups = Category.objects.filter(category_id__isnull=True) 
        serializer = self.get_serializer(mainGroups, many=True)
        
        return Response(serializer.data)

и urls.py:

router = routers.DefaultRouter()
router.register('groups', CategoryViewSet)   


urlpatterns = [
    path('', include(router.urls))
]

Итак, если я пойду на: http://127.0.0.1:8000/djangoadmin/groups/

Я получаю на выходе:

[
    {
        "id": 11,
        "category_id": null,
        "name": "zoogdieren",
        "description": "hoi",
        "animals": []
    },
    {
        "id": 12,
        "category_id": null,
        "name": "amfibieen",
        "description": "kujhkjh",
        "animals": []
    },
    {
        "id": 13,
        "category_id": null,
        "name": "vogels",
        "description": "kljhkjh",
        "animals": []
    },
    {
        "id": 16,
        "category_id": 13,
        "name": "roofvogels",
        "description": "kljhkljjl",
        "animals": []
    },
    {
        "id": 17,
        "category_id": 12,
        "name": "kikkers",
        "description": "kjhkjh",
        "animals": []
    },
    {
        "id": 21,
        "category_id": null,
        "name": "reptielen",
        "description": "reptielen",
        "animals": []
    },
    {
        "id": 22,
        "category_id": 21,
        "name": "slangen",
        "description": "slangen",
        "animals": []
    },
    {
        "id": 24,
        "category_id": 11,
        "name": "honden",
        "description": "hhhh",
        "animals": []
    },
    {
        "id": 25,
        "category_id": 11,
        "name": "katten",
        "description": "kjhkjh",
        "animals": []
    },
    {
        "id": 26,
        "category_id": 11,
        "name": "olifanten",
        "description": "kjhkjhkjh",
        "animals": []
    },
    {
        "id": 27,
        "category_id": 21,
        "name": "krokodillen",
        "description": "l;l;'ll;;'l",
        "animals": []
    },
    {
        "id": 28,
        "category_id": 22,
        "name": "cobra",
        "description": "cobra",
        "animals": [
            {
                "id": 4,
                "name": "indian cobra",
                "description": "cobra"
            },
            {
                "id": 5,
                "name": "cape cobra",
                "description": "cape cobra"
            },
            {
                "id": 6,
                "name": "Chinese cobra",
                "description": "Chinese cobra"
            }
        ]
    },
    {
        "id": 29,
        "category_id": 16,
        "name": "valken",
        "description": "valken",
        "animals": []
    },
    {
        "id": 30,
        "category_id": 16,
        "name": "gieren",
        "description": "Gieren",
        "animals": []
    },
    {
        "id": 31,
        "category_id": 21,
        "name": "aligatoren",
        "description": "aligatoren",
        "animals": []
    },
    {
        "id": 32,
        "category_id": 13,
        "name": "meeuwen",
        "description": "meeuwen",
        "animals": []
    },
    {
        "id": 33,
        "category_id": 22,
        "name": "droppel slangen",
        "description": "droppel slangen",
        "animals": []
    }
]

Так, например, zoogdieren с id 11 имеет множество связанных категорий:

  • honden category_id = 11
  • katten category_id = 11

Вопрос: Как сделать запрос, который будет фильтровать, например, по имени zoogdieren, а затем вызов api будет фильтровать ссылающиеся id?

Например, вы заполняете: http://127.0.0.1:8000/djangoadmin/groups?name=zoogdieren и в качестве вывода:

{
        "id": 24,
        "category_id": 11,
        "name": "honden",
        "description": "hhhh",
        "animals": []
    },
    {
        "id": 25,
        "category_id": 11,
        "name": "katten",
        "description": "kjhkjh",
        "animals": []
    },

Теперь в http://127.0.0.1:8000/djangoadmin/groups/11/ вы просто получаете элемент с id = 11. Если вы хотите получить все товары с category_id = 11, вам просто нужно сделать что-то вроде этого: http://127.0.0.1:8000/djangoadmin/groups?category_id=11.

Вернуться на верх