mmdfan
mmdfan

Reputation: 346

Filter objects in ManyToMany relationship by multiple criteria

I want to get the model instance of my 'Collection' object where 'request.user' is either in 'owner' or 'contributors' relationship and id of that object is 'collection_id'. Here is my code:

models.py

    class Collection(models.Model):
        title = models.CharField(max_length=250, unique=True)
        owner = models.ForeignKey(User, related_name='owner', on_delete=models.DO_NOTHING)
        contributors = models.ManyToManyField(User, related_name='contributors', blank=True)

views.py

    def collection_edit(request, collection_id)
        ...
        # Here I want to check if request.user is in contributors or owner
        collection = Collection.objects.filter(owner_id=request.user, pk=collection_id).first()
        # Do stuff
        ...

Also is 'on_delete=models.DO_NOTHING' in owner relationship going to break my database integrity if user is deleted?

Upvotes: 1

Views: 39

Answers (1)

willeM_ Van Onsem
willeM_ Van Onsem

Reputation: 477854

You can filter with Q objects:

from django.db.models import Q

Collection.objects.filter(Q(owner=request.user) | Q(contributors=request.user))

Here we thus retrieve Collection objects, for which the owner is request.user, or request.user is one of the contributors. If he is both the owner and a contributor, it will also be part of the collection.

Also is on_delete=models.DO_NOTHING in owner relationship going to break my database integrity if user is deleted?

Yes, since that means that the user_id field at that moment will contain a value of a primary key of a user that no longer exists. Most databases will however not allow that, and raise an IntegrityError. It might be better to use PROTECT if you do not want let Django remove a User if there is a still a Collection with user as owner.

Upvotes: 2

Related Questions