将F()与注释一起使用,包括Django中的另一个查询表达式

时间:2018-06-25 16:46:44

标签: django django-queryset django-1.9

这是我的(简化的)用例:

from django.db import models

class MyType(models.Model):
    whatever = models.CharField()

class A(models.Model):
    type = models.ForeignKey(MyType)

class B(models.Model):
    my_type = models.ForeignKey(MyType)
    position = models.IntegerField(default=0)

我希望A中的元素按B的位置字段排序。因此,我需要先联接MyType上的A和B表。试过这个:

A.objects.all().annotate(position=B.objects.get(my_type=models.F('type')).position).order_by('position')

得到错误:

FieldError: Cannot resolve keyword 'type' into field. Choices are: my_type, my_type_id, position

因此,Django知道F('type')试图获取模型B的'type'字段的值。当然,该字段不存在。 我想使用模型A的“类型”字段看起来像F适用于内部查询,而不适用于外部查询。

那么,有什么更好的方法来获得我想要的东西?

1 个答案:

答案 0 :(得分:0)

public MainPage()
{
    this.InitializeComponent();
    Window.Current.CoreWindow.KeyDown += CoreWindow_KeyDown;
}
private double horizontalOffset;
private double verticalOffset;
private double step = 5;
private void CoreWindow_KeyDown(Windows.UI.Core.CoreWindow sender, Windows.UI.Core.KeyEventArgs args)
{
    Debug.WriteLine("horizontalOffset: "+horizontalOffset+ " verticalOffset: "+verticalOffset);

    switch (args.VirtualKey)
    {

            case Windows.System.VirtualKey.Left: horizontalOffset = horizontalOffset-step<0 ? 0:horizontalOffset - step; scrollviewer.ChangeView(horizontalOffset,verticalOffset,1);  break;
            case Windows.System.VirtualKey.Right: horizontalOffset = horizontalOffset+step>scrollviewer.ScrollableWidth?scrollviewer.ScrollableWidth: horizontalOffset + step; scrollviewer.ChangeView(horizontalOffset,verticalOffset,1);break;
            case Windows.System.VirtualKey.Up: verticalOffset= verticalOffset - step < 0?0:verticalOffset- step; scrollviewer.ChangeView(horizontalOffset,verticalOffset,1);break;
            case Windows.System.VirtualKey.Down: verticalOffset = verticalOffset + step > scrollviewer.ScrollableHeight?scrollviewer.ScrollableHeight:verticalOffset+ step; scrollviewer.ChangeView(horizontalOffset,verticalOffset,1);break;
            default: break;
    }
}

here

获取Django版本1.11之前的django_subquery