Search code examples
djangodjango-modelsdjango-rest-frameworkdjango-viewsdjango-admin

Django movie and director relation. Movie is not attached to the director


I'm making a model, consisting of a movie and a director. When I create a movie, I want the movie to be automatically owned by the director I selected but it's not working.


class Movie(models.Model):
    name = models.CharField(max_length=100)
    category = models.CharField(max_length=100)
    imdb = models.DecimalField(max_digits=2, decimal_places=1)     
    director = models.ForeignKey('Director', on_delete=models.DO_NOTHING)

    class Meta:
        verbose_name_plural = 'Movies'

    def __str__(self):
        return self.name


class Director(models.Model):
    name = models.CharField(max_length=150)
    movies = models.ManyToManyField(Movie, related_name='movies', blank=True)

    class Meta:
        verbose_name_plural = 'Directors'

    def __str__(self):
        return self.name
    

I am creating a new movie using django-admin page. for instance;django-admin creating movie

However the movie is not automatically added to the director. Director

I also want a movie to belong to only one director. How can I do these. I will be very glad if you can help me. Thanks in advance


Solution

  • That's already the case without any need for an extra relation. Indeed, you define this as:

    class Movie(models.Model):
        name = models.CharField(max_length=100)
        category = models.CharField(max_length=100)
        imdb = models.DecimalField(max_digits=2, decimal_places=1)
        director = models.ForeignKey(
            'Director', on_delete=models.DO_NOTHING, related_name='movies'
        )
    
        class Meta:
            verbose_name_plural = 'Movies'
    
        def __str__(self):
            return self.name
    
    
    class Director(models.Model):
        name = models.CharField(max_length=150)
    
        class Meta:
            verbose_name_plural = 'Directors'
    
        def __str__(self):
            return self.name

    If you then assign a director D1 to a move M1, you can query the movies of the director with:

    D1.movies.all()

    In the modeladmin you can also display the movies when editing a Director through an inline, for example a TabularInline [Django-doc]:

    from django.contrib import admin
    
    
    class MovieInline(admin.TabularInline):
        model = Movie
    
    
    @admin.register(Director)
    class DirectorAdmin(admin.ModelAdmin):
        # …
        inlines = [
            MovieInline,
        ]