Reputation: 885
I'm working with a Posgtgresql database about movies, and I have a few Many-to-Many relationships like the following one:
There's a table with movies and each movie has some keywords, as well as two movies can have the same keyword. For that we have three tables: movies
, keywords
, and movies_keywords
.
The table named movies
is self-explanatory, it contains the title, an ID and many attributes that a movie has.
The table movies_keywords
has two columns: a movie ID and a keyword ID. This is like the "middle" that connects the two other tables.
Lastly, the table keywords
contains a keyword ID and the corresponding keyword.
The problem is the following: I'm working with Django and I need to access all the keywords for one movie, but they're not directly connected, there's this middle point that doesn't let me access the names. Do you have any idea how can this be achieved?
Thanks in advance!
EDIT: this is models.py (the relevant part)
class Movies(models.Model):
title = models.CharField(max_length=30, blank=True, null=True)
(...)
director_name = models.CharField(max_length=30, blank=True, null=True)
class Meta:
managed = False
db_table = 'movies'
class MoviesKeywords(models.Model):
movie = models.ForeignKey(Movies, models.DO_NOTHING, blank=True, null=True)
keyword = models.ForeignKey(Keywords, models.DO_NOTHING, blank=True, null=True)
class Meta:
managed = False
db_table = 'movies_keywords'
class Keywords(models.Model):
keyword = models.CharField(max_length=30, blank=True, null=True)
class Meta:
managed = False
db_table = 'keywords'
def __str__(self):
return str(self.keyword)
Upvotes: 0
Views: 165
Reputation: 15718
You want to add through to your first model ( also model table names should be singular in django -> code style )
class Movie(models.Model):
...
keywords = models.ManyToManyField('Keyword', through='MoviesKeywords', related_name='movies')
Afterwards you can access data as in many-to-many document
movie = Movie.object.filter(pk=1)
keywords = movie.keywords.all()
Upvotes: 2