【发布时间】:2019-06-08 16:24:51
【问题描述】:
我正在尝试创建一个系统,在该系统中我设置了一个问题,它会自动创建用户将定义并存储在另一个模型中的自定义字段。我将当前模型设置为与自定义字段模型的多对多关系并覆盖保存方法,以便为每个自定义字段添加默认值。
当我在保存问题模型后使用 .add 方法时,似乎什么也没发生,没有创建多对多关系。这些关系可以在 Django Admin 界面中建立。
类问题(models.Model):
class Meta:
verbose_name = "Issues"
verbose_name_plural = "Issues"
title = models.TextField(null=False, blank=False)
description = models.TextField()
owner = models.ForeignKey(Organisation, on_delete=models.CASCADE)
category = models.ForeignKey(IssueCategory, on_delete=models.CASCADE)
state = models.ForeignKey(IssueStates, on_delete=models.CASCADE)
project = models.ForeignKey(Project, on_delete=models.CASCADE)
assignedTo = models.ForeignKey(User, on_delete=models.SET_NULL, null=True)
customFields = models.ManyToManyField(IssueCustomFields, blank=True)
def save(self, *args, **kwargs):
super(Issue, self).save(*args, **kwargs)
for x in IssueCustomFieldDefinitions.objects.filter(owner=self.owner):
issueCustom = IssueCustomFields.objects.create(
value=x.default,
fieldDefinition = x,
owner = self.owner,
)
self.customFields.add(issueCustom)
print(self.customFields.all())
我希望在保存问题模型时,它会遍历用户设置的所有自定义字段并创建它的实例并建立关系。从未建立关系(尽管创建了实例)
【问题讨论】:
-
那么,IssueCustomFieldDefinitions 是什么,它与 Issue 有什么关系,以及它是如何在 admin 中填充的?
标签: python django django-models many-to-many