Django从ManyToMany中提取带有查询字段的查询集 [英] Django extract queryset from ManyToMany with through field

查看:52
本文介绍了Django从ManyToMany中提取带有查询字段的查询集的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

说我们有那些模型:

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()

是否可以选择提取B的查询集,但要考虑到订单字段?

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

执行 a.c_set.all()返回C类的查询集(但它是有序的).

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

执行 a.fields.all()可以,但是查询集是无序的.

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.

预先感谢

推荐答案

如果将 ordering 放在模型 C 上,则所有查询集都放在 C 会遵守该顺序:

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', )

现在,如果要与 A 相关的 B 对象,则可以基于 C B 进行排序的顺序:

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

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

或者如果 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', )

那么你可以做:

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

这篇关于Django从ManyToMany中提取带有查询字段的查询集的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆