简体   繁体   中英

Django extract queryset from ManyToMany with through field

Say we have those models:

class A(models.Model):
   field = models.ManyToManyField(B, through="C")

class B(models.Model):
    value = models.CharField()

class C(models.Model):
    a = models.ForeignKey(A)
    b = models.ForeignKey(B)
    order = models.IntegerField()

Is there an option to extract queryset of B's, but taking into consideration order field?

Doing a a.c_set.all() returns queryset for C class (but it's ordered).

Doing a a.fields.all() works, but the queryset is unordered.

I need a queryset for initializing the formset.

I hope it's understandable - it's quite late and i can't think clearly already... I'll try to clear it out if anyone has any questions.

Thanks in advance

If you put a an ordering on model C , all queryset on C would obey that order:

class C(models.Model):

    class Meta:
        ordering = ('order', )

Now if you want B objects related to A , you could sort the B s based on C 's ordering:

b_results = a.fields.order_by('c')

Or if the order_by('c') is not clear enough, you could change your model to be:

class C(models.Model):
    a = models.ForeignKey(A, related_name='a_relationship')
    b = models.ForeignKey(B)
    order = models.IntegerField()

    class Meta:
        ordering = ('order', )

Then you could do:

b_results = a.fields.order_by('a_relationship')

使用C模型反向关系进行排序,例如

a.fields.order_by(c__order)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM