Sascuash
Sascuash

Reputation: 3831

Django filter ManyToMany relationship from a single object

I've got an object in Django, and one of it's properties is a ManyToMany relationship. Ok, now I've got the object, and want to know if there's data related, how can I do it?

Here's the code:

u = request.user
ide = request.POST['id']
defob = DefObjc.objects.get(id=ide)
if defob.filter(student_def=u).exists():
  #do things

And here's the object class:

class DefObjc(models.Model):
  name = models.CharField(max_length=100, blank=True, null=True)
  date = models.DateTimeField(blank=True, null=True)
  student_def = models.ManyToManyField(User, related_name='DefObjc_relation', blank=True, null=True)

How can I do that?

Upvotes: 0

Views: 94

Answers (1)

Kevin Christopher Henry
Kevin Christopher Henry

Reputation: 48922

The result of get() is a model instance, not a QuerySet, so you can't filter on it. Instead:

if defob.student_def.filter(id=u.id).exists():
    # do things

Upvotes: 1

Related Questions