Django ORM SELECT加入

时间:2011-10-26 18:35:31

标签: python django django-models django-orm

ERR

django中的模型:

class Key(models.Model):
    id     = models.AutoField(primary_key=True, blank=True)
    name   = models.CharField(max_length=50)


class Record(models.Model):
    id         = models.AutoField(primary_key=True, blank=True)
    project_id = models.IntegerField()
    name       = models.CharField(max_length=50)


class Value(models.Model):
    id        = models.AutoField(primary_key=True, blank=True)
    record    = models.ForeignKey(Record)
    key       = models.ForeignKey(Key)
    value     = models.CharField(max_length=255)

我需要从DB中选择这个数据:

NAME (from record)
and fields related with this record
[NAME (from key), VALUE (from value)]
[NAME (from key), VALUE (from value)]
[...]

我可以使用django ORM进行此选择吗? (例如在SQL select中看起来像这样)

SELECT
    `keeper_record`.`id` AS `record_id`,
    `keeper_record`.`name` AS `name`,
    `keeper_record`.`desc` AS `desc`,
    `keeper_key`.`name` AS `key_name`,
    `keeper_key`.`desc` AS `key_desc`,
    `keeper_value`.`value` AS `value_value`
FROM `keeper_record`
JOIN `keeper_value` ON `keeper_record`.`id` = `keeper_value`.`record_id`
JOIN `keeper_key` ON `keeper_key`.`id` = `keeper_value`.`key_id`
WHERE record_id = id

2 个答案:

答案 0 :(得分:8)

以下选择与特定记录ID相关的值。然后,您可以按照外键获取相关记录和密钥。使用select_related可以最大限度地减少数据库查找。

# Select all values related to a record in your view
record = Record.objects.get(pk=record_id)
values = Value.objects.filter(record=record).select_related()

# In your template
{% for value in values %}
{{ value.record.name }} - {{ value.key.name }} - {{ value.value }}
{% endfor %}

选择多一条记录

在你的sql中,你有WHERE record_id = 1,所以我展示了如何获取特定记录的所有值。您还可以在一个查询中为多条记录选择多个值。

# filter all records which belong to the project with `project_id=1`
records = Record.objects.filter(project_id=1)
# select all values that belong to these records
values = Value.objects.filter(record__in=records).select_related().order_by('record')

答案 1 :(得分:2)

应该相对简单,因为你已经将外键绑在一起了。

Record.objects.select_related().filter(id = variable_that_stores_id)

您可以将其与only结合使用,以限制您想要带回的字段。