【发布时间】:2017-11-16 11:58:04
【问题描述】:
我有两个模型:MetaModel 和 RelatedModel。我想在MetaModel 查询中包含RelatedModel 查找的结果,并且我想在单个数据库调用中执行此操作。
我尝试定义一个“子查询”QuerySet 以在主查询中使用,但这没有奏效 - 它仍在进行两个查询来完成操作。
注意:我不能使用传统的ForeignKey 关系,因为profile_id 字段不是唯一的。唯一性是profile_id 和channel 的组合。这是一个聚合表,profile_id 不保证在多个第三方渠道中是唯一的。
有什么建议吗?
型号:
class Channel(models.Model):
id = models.AutoField(primary_key=True)
name = models.CharField(
max_length=25,
)
class MetaModel(models.Model):
profile_id = fields.IntegerField()
channel = fields.ForeignKey(Channel))
metadata = fields.TextField()
class RelatedModel(models.Model):
related_id = fields.IntegerField()
profile_id = fields.IntegerField()
channel = fields.ForeignKey(Channel))
虚拟数据
channel = Channel("Web site A")
channel.save()
sample_meta = MetaModel(profile_id=1234, channel=channel)
sample_related = RelatedModel(profile_id=1234, related_id=5678, channel=channel)
查询:
# Create a queryset to filter down to the single record we need the `profile_id` for
# I've limited to the only field we need via a `values` operation
related_qs = RelatedAccount.objects.filter(
related_id=5678,
channel=channel
).values_list("profile_id", flat=True)
# I'm doing an update_or_create as there is other data to store, not included for brevity
obj, created = MetaModel.objects.update_or_create(
profile_id=related_qs.first(), # <<< This var is the dynamic part of the query
channel=channel,
defaults={"metadata": "Metadata is added to a new or existing record."}
)
【问题讨论】:
标签: python django postgresql