Django ManyToManyField ordering using through

后端 未结 7 2330
傲寒
傲寒 2020-12-13 20:27

Here is a snippet of how my models are setup:

class Profile(models.Model):     
    name = models.CharField(max_length=32)

    accout = models.ManyToManyFie         


        
相关标签:
7条回答
  • 2020-12-13 21:02

    I have this on a number of my models, but in my opinion (and unlike all the other answers) you shouldn't need to specify the order_by again because, well, it's already specified in the through model. Specifying it again breaks the DRY (don't repeat yourself) principle.

    I would use:

    qs = profile.profileaccounts_set.all()
    

    This gives the set of ProfileAccounts associated with a profile using your configured ordering. Then:

    for pa in qs:
        print(pa.account.name)
    

    For bonus points, you can also speed up the overall process by using select_related in the query.

    0 讨论(0)
提交回复
热议问题