This post has been de-listed
It is no longer included in search results and normal feeds (front page, hot posts, subreddit posts, etc). It remains visible only via the author's post history.
5
Filtering Data from a model having ManyToManyField
Post Body
I have created three models as shown below. I am trying to get all movies a particular actor is part of. As an example, if I have created three movies with title 'Movie1', 'Movie2' and 'Movie3', and an actor named 'Actor 1' is part of two of the movies, I want to write a query to return these two movie names when the 'role' in the Role model is ACTOR. Kindly guide me on how this can be done as I am really struggling to understand how to query data from ManyToManyField.
from django.db import models
from django.shortcuts import reverse
class Actor(models.Model):
first_name = models.CharField(max_length=100)
last_name = models.CharField(max_length=100, blank=True)
slug = models.SlugField(max_length=100, unique=True)
def __str__(self):
if self.first_name and self.last_name:
return f"{self.first_name} {self.last_name}"
else:
return self.first_name
def get_full_name(self):
if self.first_name and self.last_name:
return f"{self.first_name} {self.last_name}"
else:
return self.first_name
def get_absolute_url(self):
return reverse('actors-detail', kwargs={'slug': self.slug})
class Movie(models.Model):
title = models.CharField(max_length=255)
slug = models.CharField(max_length=255, unique=True)
actors = models.ManyToManyField(Actor,
related_name='movies',
default=None,
null=True,
blank=True)
def __str__(self):
return self.title
def get_absolute_url(self):
return reverse('movies-detail', kwargs={'slug': self.slug})
class Role(models.Model):
ROLE_CHOICES = (
('ACTOR', 'ACTOR'),
('DIRECTOR', 'DIRECTOR'),
('PRODUCER', 'PRODUCER'),
)
name = models.CharField(max_length=50)
role_type = models.CharField(max_length=10,
choices=ROLE_CHOICES,
default='ACTOR')
actor = models.ForeignKey(Actor, on_delete=models.CASCADE)
movie = models.ForeignKey(Movie, on_delete=models.CASCADE)
Author
User Disabled
Account Strength
0%
Disabled 4 months ago
Account Age
5 years
Verified Email
Yes
Verified Flair
No
Total Karma
6,531
Link Karma
663
Comment Karma
5,737
Profile updated: 4 days ago
Posts updated: 1 year ago
Subreddit
Post Details
We try to extract some basic information from the post title. This is not
always successful or accurate, please use your best judgement and compare
these values to the post title and body for confirmation.
- Posted
- 4 years ago
- Reddit URL
- View post on reddit.com
- External URL
- reddit.com/r/djangolearn...