[Answered ]-Django Rest Framework : managing relations

2👍

First of all you have to rethink the design of your models. As described in the opening, there is a many-to-many relationship between movies and sources. movieSources would be the intermediate table, which isn’t necessary to be declared as a model, as Django’s ORM takes care about that.

Also I would suggest you to follow the conventions and write your model class names in PascalCase. Use rather singular names for this purpose.

models.py

class Movie(models.Model):
    short_desc = models.CharField('short description', max_length=255)
    uploaded = models.DateTimeField('date published', auto_now=True)

    class Meta:
        db_table = 'movies'


class Source(models.Model):
    name = models.CharField(max_length=50)
    create_date = models.DateTimeField('date published', auto_now=True)
    movies = models.ManyToManyField(Movie, related_name='sources')

    class Meta:
        db_table = 'sources'

So should the models look like according to your description. The option auto_now=True will create automatically the timestamp when an entry is created. The models are connected with a m:n relation. Django takes care for everything else behind the doors.

Now you can create your serializers:

serializers.py

class MovieSerializer(serializers.ModelSerializer):
    sources = serializers.PrimaryKeyRelatedField(many=True)

    class Meta:
        model = Movie
        fields = (short_desc, uploaded, sources)


class SourceSerializer(serializers.ModelSerializer):
    movies = serializers.PrimaryKeyRelatedField(many=True)

    class Meta:
        model = Source
        fields = (name, create_date, movies)

The PrimaryKeyRelatedField will fetch the related data.

I didn’t test the code and wrote it as I remember, but I think it should work out of the box. I hope the answer helps you and gives you an idea how to solve your problem better.

👤cezar

Leave a comment