我这里有 3 个模型需要处理:SurveyQuestion
、Update
和Notification
。每当创建或 的实例时,我都会使用post_save
信号来创建模型的实例。Notification
SurveyQuestion
Update
该Notification
模型有一个GenericForeignKey
,它指向创建它的模型。在通知模型中,我尝试使用设置ForeignKey
为__str__
创建title
它的模型实例的字段。如下所示:
class Notification(models.Model):
source_object = models.ForeignKey(ContentType, on_delete=models.CASCADE)
object_id = models.PositiveIntegerField()
source = GenericForeignKey("source_object", "object_id")
#more stuff
def __str__(self):
return f'{self.source.title} notification'
我能够从管理面板创建 SurveyQuestion 和 Update 的实例,然后(应该)创建 Notification 的实例。但是,当我Notification
在 shell 中查询实例时:
from hotline.models import Notification
notifications = Notification.objects.all()
for notification in notifications:
print (f"Notification object: {notification}")
NoneType
---------------------------------------------------------------------------
AttributeError Traceback (most recent call last)
1 for notification in notifications:
----> 2 print (notification)
File ~/ygzsey/hotline/models.py:27, in Notification.__str__(self)
26 def __str__(self):
---> 27 return f'{self.source.title} notification'
AttributeError: 'NoneType' object has no attribute 'title'
当我查询以下实例时SurveyQuestion
:
from hotline.models import SurveyQuestion
surveys = SurveyQuestion.objects.all()
for survey in surveys:
print (f"Model: {survey.__class__.__name__}")
Model: SurveyQuestion
当我查询实例Notification
并尝试打印其字段的类名ForeignKey
(我将其标记为source
)时,我得到了以下信息:
for notification in notifications:
print (f"Notification for {notification.source.__class__.__name__}")
Notification for NoneType
Notification for NoneType
Notification for NoneType
因此看起来SurveyQuestion
,、Update
和Notification
实例都保存正常,但是存在一些问题GenericForeignKey
。
我已经使用post_save
创建了一个实例,但是当我尝试在管理面板中保存或的实例时会出现错误:Notification
Notification(source_object=instance, start_date=instance.start_date, end_date=instance.end_date)
SurveyQuestion
Update
ValueError at /admin/hotline/update/add/
Cannot assign "<Update: Update - ad>": "Notification.source_object" must be a "ContentType" instance.
所以我将其改为Notification(source_object=ContentType.objects.get_for_model(instance), start_date=instance.start_date, end_date=instance.end_date)
。
我的完整models.py
:
from django.db import models
from datetime import timedelta
from django.utils import timezone
from django.contrib.contenttypes.fields import GenericForeignKey, GenericRelation
from django.contrib.contenttypes.models import ContentType
from django.db.models.signals import post_save
from django.dispatch import receiver
def tmrw():
return timezone.now() + timedelta(days=1)
class Notification(models.Model):
source_object = models.ForeignKey(ContentType, on_delete=models.CASCADE)
object_id = models.PositiveIntegerField()
source = GenericForeignKey("source_object", "object_id")
start_date = models.DateTimeField(default=timezone.now)
end_date = models.DateTimeField(default=tmrw)
class Meta:
verbose_name = 'Notification'
verbose_name_plural = f'{verbose_name}s'
def __str__(self):
return f'{self.source.title} notification'
class Update(models.Model):
title = models.CharField(max_length=25)
update = models.TextField()
start_date = models.DateTimeField(default=timezone.now)
end_date = models.DateTimeField(default=tmrw)
#notification = GenericRelation(Notification, related_query_name='notification')
class Meta:
verbose_name = 'Update'
verbose_name_plural = f'{verbose_name}s'
def __str__(self):
return f'{self.__class__.__name__} - {self.title}'
class SurveyQuestion(models.Model):
title = models.CharField(max_length=25)
question = models.TextField()
start_date = models.DateTimeField(default=timezone.now)
end_date = models.DateTimeField(default=tmrw)
#notification = GenericRelation(Notification, related_query_name='notification')
class Meta:
verbose_name = 'Survey'
verbose_name_plural = f'{verbose_name}s'
def __str__(self):
return f'{self.__class__.__name__} - {self.title}'
class SurveyOption(models.Model):
survey = models.ForeignKey(SurveyQuestion, on_delete=models.CASCADE, related_name='options')
option = models.TextField()
id = models.AutoField(primary_key=True)
class Meta:
verbose_name = 'Survey option'
verbose_name_plural = f'{verbose_name}s'
def __str__(self):
return f'{self.survey.title} option #{self.id}'
@receiver(post_save)
def create_notification(instance, **kwargs):
#"""
print (f"instance: {instance}")
print (f"instance.__class__: {instance.__class__}")
print (f"instance.__class__.__name__: {instance.__class__.__name__}")
#"""
senders = ['SurveyQuestion', 'Update']
if instance.__class__.__name__ in senders:
notification = Notification(source_object=ContentType.objects.get_for_model(instance), start_date=instance.start_date, end_date=instance.end_date)
notification.save()
post_save.connect(create_notification)
您应该使用
source
,而不是:source_object
A
GenericForeignKey
本质上结合了两列,source_object
指向所指项目类型GenericForeignKey
的(非常糟糕的名称)和存储该对象的主键(或另一个唯一列)的列。