您没有在提取的对象中引用M2M字段。你需要解决
sample
字段如下:
型号.py:
@classmethod
def add_to_container(cls, current_container, new_sample):
containerContents, created = cls.objects.get_or_create(
current_container=current_container
)
containerContents.sample.add(new_sample)
@classmethod
def remove_from_container(cls, current_container, new_sample):
containerContents, created = cls.objects.get_or_create(
current_container=current_container
)
containerContents.sample.remove(new_sample)
并为模型方法设置适当的变量:
视图.py
def change_container(request, operation, pk, fk='', sample_id=''):
container = Container.objects.get(pk=pk)
sample = Sample.objects.get(pk=fk)
# sample = Container.objects.get(container.sample_id=sample_id)
if operation == 'add':
ContainerContents.add_to_container(container, sample)
elif operation == 'remove':
ContainerContents.remove_from_container(container, sample)
return redirect('depot:allcontainer')