Django将外部字段添加到查询中

时间:2017-09-28 18:12:32

标签: django django-models django-queryset

我有两张表:menufoodtype

class Foodtype(models.Model):
    foodtype_en = models.TextField()
    active = models.BooleanField()

    class Meta:
        managed = False
        db_table = 'foodtype'

class Menu(models.Model):
    title_en = models.TextField()
    description_en = models.TextField()
    active = models.BooleanField()
    id_foodtype = models.ForeignKey(Foodtype, models.DO_NOTHING, 
    id_home = models.ForeignKey('Home', models.DO_NOTHING, db_column='id_home')

    class Meta:
        managed = False
        db_table = 'menu'

另外,我生成了一个组合表:

class MenuSerializer(serializers.ModelSerializer):
    foodtype_en = serializers.CharField()
    class Meta:
        model = Menu
        fields = ('id', 'title_en', 'active')

我正试图获取所有有效的menu条记录。

我有:

menu = Menu.objects.filter(id_home=3,active=True).annotate(foodtype=foodtype)

我的查询有什么问题?

1 个答案:

答案 0 :(得分:1)

看起来像你需要source

foodtype_en = serializers.CharField(source='id_foodtype.foodtype_en')