How do I extend the Django Group model?

前端 未结 4 1055
Happy的楠姐
Happy的楠姐 2020-12-01 02:12

Is there a way to extend the built-in Django Group object to add additional attributes similar to the way you can extend a user object? With a user object, you can do the fo

4条回答
  •  情话喂你
    2020-12-01 02:28

    You can create a model that subclasses Group, add your own fields, and use a Model Manager to return any custom querysets you need. Here's a truncated example showing how I extended Group to represent Families associated with a school:

    from django.contrib.auth.models import Group, User
    
    class FamilyManager(models.Manager):
        """
        Lets us do querysets limited to families that have 
        currently enrolled students, e.g.:
            Family.has_students.all() 
        """
        def get_query_set(self):
            return super(FamilyManager, self).get_query_set().filter(student__enrolled=True).distinct()
    
    
    class Family(Group):
        notes = models.TextField(blank=True)
    
        # Two managers for this model - the first is default 
        # (so all families appear in the admin).
        # The second is only invoked when we call 
        # Family.has_students.all()  
        objects = models.Manager()
        has_students = FamilyManager()
    
        class Meta:
            verbose_name_plural = "Families"
            ordering = ['name']
    
        def __unicode__(self):
            return self.name
    

提交回复
热议问题