Django ORM:当我实例化一个新对象时选择查询

时间:2017-11-16 10:02:32

标签: python django postgresql django-models

我有这些模特:

class Alarm(ModelWithValidation):
    datetime = models.DateTimeField(auto_now_add=True, db_index=True)
    value = models.TextField(null=True, blank=True)
    description = models.TextField()
    reading = GenericForeignKey('content_type', 'object_id')
    content_type = models.ForeignKey(ContentType,
                                     null=True,
                                     blank=True)
    object_id = models.PositiveIntegerField(null=True, blank=True)


class SolarMeterReading(ModelWithValidation):
    datetime = models.DateTimeField(db_index=True, auto_now_add=True)
    irradiance = RoundedDecimalField(max_digits=15, decimal_places=2,
                                     null=True, blank=True)
    name = models.CharField(db_index=True, max_length=30)
    alarms = GenericRelation(Alarm)

我注意到当我实例化SolarMeterReading时,Django会进行SELECT查询:

SolarMeterReading(name='test', alarms=[])

查询:

SELECT "api_alarm"."id", "api_alarm"."datetime", 
"api_alarm"."value", "api_alarm"."description", 
"api_alarm"."content_type_id", 
"api_alarm"."object_id" FROM "api_alarm" WHERE 
("api_alarm"."object_id" IS NULL AND "api_alarm"."content_type_id" = 18);

为什么Django会进行此查询? 如果SolarMeterReading尚未保存在数据库中,则没有理由搜索相关的警报。

0 个答案:

没有答案