我明白它希望我在我訪問M2M字段之前保存。我不想保存模型。我正在使用稱爲TaskSearchCriteria的模型來搜索任務。用戶可以選擇將標準保存到數據庫以備將來搜索。但應該可以在不保存標準的情況下進行一次搜索。這是我的模型。Django - 實例需要有一個主鍵值才能使用多對多的關係
class TaskSearchCriteria(models.Model):
name = models.CharField(max_length=256)
task_name = models.CharField(max_length=256, blank=True, null=True)
project = models.ForeignKey(Project, blank=True, null=True)
sprint = models.ForeignKey(Sprint, blank=True, null=True)
type = models.ForeignKey(TaskType, blank=True, null=True)
priority = models.ForeignKey(Priority, blank=True, null=True)
status = models.ForeignKey(Status, blank=True, null=True)
description = models.CharField(max_length=1024, blank=True, null=True)
owner = models.ForeignKey(User)
users = models.ManyToManyField(User, related_name='a+')
def get_param_dict(self):
retval = dict()
if self.task_name != None and len(self.task_name) > 0:
retval["name__contains"] = self.task_name
if self.project != None:
retval["project__id"] = self.project.pk
if self.sprint != None:
retval["sprint__id"] = self.sprint.pk
if self.type != None:
retval["type__id"] = self.type.pk
if self.priority != None:
retval["priority__id"] = self.priority.pk
if self.status != None:
retval["status__id"] = self.status.pk
if self.description != None and len(self.description) > 0:
retval["description__contains"] = self.description
if self.users != None and len(self.users) > 0: #**ERROR HERE**
ids = [user.pk for user in self.users]
retval["users__in"] = ids
return retval
我使用的模型形式創建模型和運行get_param_dict()方法來創建字典用於model.object.filter()。是否可以在不保存數據庫的情況下使用m2m字段?
這個工作!謝謝您的幫助。 – 2013-04-10 01:23:11