此问题与这些a和b类似,但差别不大。我是django的新手,所以请耐心等待。以下是我的模特
class Project(UniqueIdentifier):
status = models.CharField(max_length=2)
class User(UniqueIdentifier):
first_name = models.CharField(max_length=50,blank=False,null=False)
last_name = models.CharField(max_length=50,blank=False,null=False)
email_address = models.EmailField(max_length=200)
user_state = models.BooleanField()
class Meta:
abstract = True
class Employee(User):
experience = models.DecimalField(max_digits=4, decimal_places=2)
userType = models.CharField(max_length=2,choices=USER_TYPES)
class Team(UniqueIdentifier):
role = models.CharField(max_length=2)
members = models.ManyToManyField(Employee, through="TeamMember")
belongsTo = models.ForeignKey(Project, related_name="team")
class TeamMember(UniqueIdentifier):
team = models.ForeignKey(Team)
members = models.ForeignKey(Employee)
和我的通用视图类
class ProjectView(UpdateView):
model = Project
fset = inlineformset_factory(Project,Team,form=TeamForm,can_delete=False,fk_name="belongsTo",extra=0)
def get_object(self, *args, **kwargs):
c = get_object_or_404(Project, unique_id = self.kwargs.get('cid'))
df = ProjectForm(instance=c)
.......
return c
def get_context_data(self, *args, **kwargs):
context = super(ProjectUpdateView, self).get_context_data(*args, **kwargs)
..........
return context
def form_valid(self,form,*args, **kwargs):
c = get_object_or_404(Project, unique_id = self.kwargs.get('cid'))
if self.request.method == "POST":
df = ProjectForm(self.request.POST, instance = c)
if df.is_valid():
c = df.save()
fs = self.fset(self.request.POST,instance=c)
if fs.is_valid():
k=fs.save()
我收到此错误。
Cannot set values on a ManyToManyField which specifies an intermediary model.
请建议是否有人有其他解决方案(我真的不想将逻辑分散到单独的表格中)。感谢您的帮助,谢谢!
**更新:找到了解决方案here。这是我的解决方案,
Class ProjectView(CreateView):
.........
def form_valid():
.........
if fs.is_valid():
k=fs.save(commit=False)
for h in k:
h.save()
for x in range(0,len(k)):
for y in self.request.POST.getlist('team-'+str(x)+'-members'):
p=TeamMember(team=k[x],members=get_object_or_404(Employee,unique_id=y))
p.save()
非常感谢!
答案 0 :(得分:2)
如果你包含了一个堆栈跟踪(而不仅仅是错误)会有所帮助。但从它的外观来看,你需要保存中间模型的实例:
引自the docs:
现在您已将ManyToManyField设置为使用中间模型,您已准备好开始创建一些多对多关系。您可以通过创建中间模型的实例来完成此操作...与普通的多对多字段不同,您不能使用添加,创建或赋值来创建关系...创建此类关系的唯一方法是创建中间模型的实例。