Asi*_*tar 2 django django-models
我正在尝试在为 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)
Run Code Online (Sandbox Code Playgroud)
这是我的报价表
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)
Run Code Online (Sandbox Code Playgroud)
这是我的视图功能:
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
)
Run Code Online (Sandbox Code Playgroud)
当您使用 , 时Quotation.objects.create,Django 会自动创建对象并将其保存到数据库中。因此,quotation.save()应该删除,因为它是不必要的。
最重要的是,使用User(...)不会将对象保存到数据库中。在插入用户 for和外键之前,您仍然需要调用save或使用上述解决方案 ( create) 。senderreceiver
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
)
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
6296 次 |
| 最近记录: |