How to remove an object from ManyToMany relationsh

2019-09-04 06:50发布

问题:

I have a model with ManyToMany relationship.

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

Serializers:

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')

I am able to add a file object to the folder. I am able to update the name of the folder too. But how do I remove a file object from the folder?

回答1:

If you are accessing from files

file = File.objects.get(query)

Then you can do

file.folders.remove(folder_object)

Edit: Your app's urls file:

urls.py:

from django.conf.urls import include, url
from .views import folder
urlpatterns = [
    url(r'remove-folder/', folder, name='remove_folder'),
]

Your apps views.py:

def folder(request):
    file = File.objects.get(query)
    file.folders.remove(folder_object)
    # return appropriate data