Home > database >  how can I store more objects from another class in other classes Field
how can I store more objects from another class in other classes Field

Time:11-18

I've been looking for my problem in Django documentation and couldn't find solution. My problem is that in Api Pannel I cannot insert more objects from "ActorsAndDirectors" class into "cast" Field in "Movie" class. I can only insert one. How to transfrom cast field so I could insert multiple objects from "ActorsAndDirectors" class into "Movie" class

this is the code `

class ActorsAndDirectors(models.Model):
    name = models.CharField(max_length=32, blank=False, null=False)
    surname = models.CharField(max_length=32, blank=False, null=False)
    role = models.CharField(max_length=11, blank=False, null=False)

    def __str__(self):
        return f"{self.name} {self.surname}"


class Movie(models.Model):
    title = models.CharField(max_length=50, blank=False, null=False, unique=True)
    description = models.TextField(max_length=400)
    cast = models.ForeignKey(ActorsAndDirectors, on_delete=models.CASCADE)
    premiere = models.DateField()
    updated = models.DateTimeField()
    slug = models.SlugField()

    def number_of_ratings(self):
        return Rating.objects.filter(movie=self).count()
    
    def avg_rating(self):
        score = 0
        ratings = Rating.objects.filter(movie=self)
        for rating in ratings:
            score  =rating.stars
        if len(ratings) > 0:
            return score/len(ratings)
        else:
            return 0

    def __str__(self):
        return f"{self.title}, ({self.premiere})"

`

I looked through Django documentation for some kind of list Field but with no good results. Im looking for help how to transform the field or maybe some other explanation of my problem

CodePudding user response:

What you are looking for is a Many to Many relation. Where many actors and directors can participate in many different movies.

I would like to complement that when querying the database its slower to look for strings. Maybe you should check this choices option for your ActorsAndDirectors role field.

This would help if you try to filter directors or actors later on. Another option would be a Table and a FK.

  • Related