简体   繁体   English

Django通过through字段从ManyToMany中提取查询集

[英]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? 是否可以提取B的查询集,但要考虑订单字段?

Doing a a.c_set.all() returns queryset for C class (but it's ordered). 执行a.c_set.all()返回C类的queryset(但它是有序的)。

Doing a a.fields.all() works, but the queryset is unordered. 执行a.fields.all()可以,但是queryset是无序的。

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: 如果你把一个ordering型号C ,所有的查询集C会服从的顺序:

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: 现在,如果您想要与A相关的B对象,则可以根据C的排序对B进行排序:

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

Or if the order_by('c') is not clear enough, you could change your model to be: 或者,如果order_by('c')不够清晰,则可以将模型更改为:

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)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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