Django: Order a model by a many-to-many field

后端 未结 3 1727
鱼传尺愫
鱼传尺愫 2021-02-07 21:19

I am writing a Django application that has a model for People, and I have hit a snag. I am assigning Role objects to people using a Many-To-Many relationship - where Roles have

3条回答
  •  广开言路
    2021-02-07 22:03

    Here's a way to do it without an annotation:

    class Role(models.Model):
        pass
    
    class PersonRole(models.Model):
        weight = models.IntegerField()
        person = models.ForeignKey('Person')
        role = models.ForeignKey(Role)
    
        class Meta:
            # if you have an inline configured in the admin, this will 
            # make the roles order properly 
            ordering = ['weight'] 
    
    class Person(models.Model):
        roles = models.ManyToManyField('Role', through='PersonRole')
    
        def ordered_roles(self):
            "Return a properly ordered set of roles"
            return self.roles.all().order_by('personrole__weight')
    

    This lets you say something like:

    >>> person = Person.objects.get(id=1)
    >>> roles = person.ordered_roles()
    

提交回复
热议问题