我将教师的CharField更改为ManyToManyField,现在我的UserMessage和EmailMessage已损坏,
模型如下:
class UserMessage(models.Model):
user = models.ManyToManyField(User,related_name="recipent")
send_user = models.ForeignKey(Use,null=True, blank=True, on_delete=models.SET_NULL, related_name="sender")
message = models.CharField(max_length=500)
test_name =models.CharField(max_length=800, default='', blank=True)
test_date = models.DateField(default=datetime.now)
test_time = models.TimeField(default=datetime.now)
`# when teacher is not ManyToManyField, the EmailMessage of body works well with test.teacher.user`
teacher = models.ManyToManyField(User, related_name="+")
test.teacher.username
用于CharField,如何定义ManyToManyField?
body="Name of test:" + test.name + ",Date :" + str(test.date) + ",Time:" + str(test.time) + ", Teachers:" + test.teacher.username
以及如下所示的UserMessage的部分views.py(不是完整代码),UserMessage的功能运行良好,但是我想知道如何将form.cleaned_data['teacher'].username
更改为ManyToManyFiled吗?我的意思是不是form.cleaned_data['teacher.set()']
或其他任何东西,非常感谢您的任何建议。
user_message.test_name = form.cleaned_data['name']
user_message.teacher = form.cleaned_data['teacher'].username
user_message.test_time = form.cleaned_data['time']
user_message.test_date = form.cleaned_data['date']
答案 0 :(得分:0)
要设置外键而不是其字段之一时,必须分配User实例。假设老师是一个用户对象,您可以使用类似的
for user_teacher in form.cleaned_data['teacher']:
user_message.teacher.add(user_teacher)
如果您没有传递用户实例(仅说一个用户名),您将不得不以某种方式选择相关的教师,然后添加m2m关系,例如
user_teacher = get_object_or_404(get_user_model(), username=form.cleaned_data['teacher'])
user_message.teacher.add(user_teacher)
在您的用户名唯一的情况下可以使用。