Creating efficient database queries for hierarchical models (django)

后端 未结 3 1761
我在风中等你
我在风中等你 2021-02-06 12:07

Consider this (django) model:

class Source(models.Model):
   # Some other fields
   type = models.ForeignKey(\'Type\')

class Type(models.Model):
    # Some othe         


        
3条回答
  •  -上瘾入骨i
    2021-02-06 12:20

    django-mptt or django-treebeard are great helpers for hierarchical data. They both add extra metadata to your model to allow efficient queries.

    if you choose to use django-treebeard your model could look something like this:

    from django.db import models
    from treebeard.mp_tree import MP_Node
    
    class Source(models.Model):
        # Some other fields
        type = models.ForeignKey('Type')
    
    class Type(MP_Node):
        # Some other fields
        name = models.CharField(max_length=100)
    
        # parent gets added automatically by treebeard
        # parent = models.ForeignKey('self', blank=True, null=True)
    

    and could be queried like this:

    # get all Sources of Type type and descendants of type
    type = Type.objects.get(name='Radio')
    Source.objects.filter(type__in=type.get_descendants())
    

    see https://django-treebeard.readthedocs.io/en/latest/api.html for more possible queries

提交回复
热议问题