我有一个与ManyToMany关系的模型。
class File(models.Model):
name = models.CharField(max_length=64)
def __str__(self):
return self.name
class Folder(models.Model):
name = models.CharField(max_length=64)
files = models.ManyToManyField(File, related_name='folders', default=None)
def __str__(self):
return self.name
串行器:
class FileSerializer(serializers.ModelSerializer):
class Meta:
model = models.File
fields = '__all__'
class FolderSerializer(serializers.ModelSerializer):
files = FileSerializer(many=True, read_only=True)
file = serializers.PrimaryKeyRelatedField(queryset=models.File.objects.all(),
write_only=True, label='File Name')
class Meta:
model = models.Folder
fields = ('id', 'name', 'files', 'file')
我可以将文件对象添加到该文件夹中。我也可以更新文件夹的名称。但是如何从文件夹中删除文件对象?
答案 0 :(得分:1)
如果您从文件中访问
file = File.objects.get(query)
然后你可以做
file.folders.remove(folder_object)
编辑: 您应用的网址文件:
urls.py:
from django.conf.urls import include, url
from .views import folder
urlpatterns = [
url(r'remove-folder/', folder, name='remove_folder'),
]
您的应用视图views.py:
def folder(request):
file = File.objects.get(query)
file.folders.remove(folder_object)
# return appropriate data