我正在尝试在为Quotation创建对象时创建Message obj。我试过看官方的Django文档,但似乎并不适用。我不知道错误在哪里。
class Message(models.Model):
sender = models.ForeignKey(User, related_name="sender_user")
recipient = models.ForeignKey(User, related_name="recipient_user")
sender_read = models.BooleanField(default=False)
recipient_read = models.BooleanField(default=False)
parent_msg = models.ForeignKey("self", null=True, blank=True, related_name="parent")
subject = models.CharField(max_length=255, blank=True, null=True)
message = models.TextField(null=True, blank=True)
created = models.DateTimeField(auto_now_add=True, null=True, blank=True)
这是我的报价表
class Quotation(models.Model):
editor = models.ForeignKey(Editors)
discipline = models.ForeignKey(Discipline, null=True, blank=True)
title = models.CharField(max_length=255)
description = models.TextField(null=True, blank=True)
words_count = models.CharField(max_length=255)
student = models.ForeignKey(Students, null=True, blank=True)
created = models.DateTimeField(auto_now_add=True, null=True, blank=True)
modified = models.DateTimeField(auto_now=True, null=True, blank=True)
这是我的观点功能:
quotation = Quotation.objects.create(
editor=editor,
student=student,
title=form.cleaned_data['title'],
discipline = discipline,
description = form.cleaned_data['description'],
words_count=form.cleaned_data['words_count']
)
quotation.save()
create_message = Message.objects.create(
sender= User(username=quotation.student.user.username),
recipient=User(username=quotation.editor.user.username),
subject=quotation.title,
messages=quotation.description
)
答案 0 :(得分:4)
当您使用Quotation.objects.create
时,Django将自动创建并将对象保存到数据库。因此,quotation.save()
应该被移除,因为它是不必要的。
除此之外,使用User(...)
不会将对象保存到数据库中。在插入save
和create
外键的用户之前,您仍需要调用sender
或使用上述解决方案(receiver
)。
views.py
:
quotation = Quotation.objects.create(
editor=editor,
student=student,
title=form.cleaned_data['title'],
discipline = discipline,
description = form.cleaned_data['description'],
words_count=form.cleaned_data['words_count']
)
sender = User.objects.create(username=quotation.student.user.username)
receiver = User.objects.create(username=quotation.editor.user.username)
create_message = Message.objects.create(
sender= sender,
recipient=receiver,
subject=quotation.title,
messages=quotation.description
)