如何从联接表中选择值?

时间:2019-09-30 13:32:34

标签: django django-models django-orm

我有两个模型,

class model_1(models.Model):
    id = models.IntegerField(primary_key=True)
    tableName = models.CharField(max_length=20, default=None)

    class Meta:
        db_table = "table1"

class model_2(models.Model):
    id = models.IntegerField(primary_key=True)
    tableId = models.ForeignKey(model_1, on_delete=models.CASCADE, db_column='tableId')

    class Meta:
        db_table = "table2"

我在表演,

queryset = model_2.objects.select_related('tableId').values('tableName').annotate(tcount=Count('tableId'))

我想要以下查询

select table1.tableName, count(table2.tableId) from table2 INNER JOIN `table1` ON (`table1`.`id` = `table2`.`tableId`) group by table2.tableId; 

但它给了我

django.core.exceptions.FieldError: Cannot resolve keyword 'tableName' into field. Choices are: tableId, id

谢谢您的建议

0 个答案:

没有答案