Django Rest Framework:管理关系

时间:2016-01-22 10:14:22

标签: django django-rest-framework

我有以下3个表

电影 ID | shortDesc |上传

源 ID |名字| CREATEDATE

movieSources movieID |的sourceID

如何将它们全部链接在一起以获取一个REST调用中的所有数据 我有以下代码,它似乎没有工作

models.py

class movieSources(models.Model):
        class Meta:
                db_table = "movieSources"
        movieID = models.IntegerField()
        sourceID = models.IntegerField()

class movies(models.Model):
        class Meta:
                db_table = 'movies'
        uploaded = models.DateTimeField('date published')
        sourcesMovie = models.OneToOneField(movieSources)

class sources(models.Model):
        class Meta:
                db_table = 'sources'
        createDate = models.DateTimeField('date published')

Serializers.py

class MovieSourcesSerializer(serializers.ModelSerializer):
        class Meta:
            model = movieSources

        fields = ('movieID', 'sourceID')


class MoviesSerializer(serializers.ModelSerializer):

    sourceID = serializers.IntegerField(source='sourcesMovie.sourceID')

    class Meta:
        model = movies

    fields = ('id','uploaded', 'sourceID')

1 个答案:

答案 0 :(得分:2)

首先,您必须重新考虑模型的设计。如开头所述,moviessources之间存在多对多关系。 movieSources将是中间表,因为Django的ORM会对此进行处理,因此无需将其声明为模型。

另外,我建议您遵循约定并在PascalCase中编写模型类名称。为此目的使用相当奇异的名称。

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'

模型应该根据您的描述看起来如此。选项auto_now=True将在创建条目时自动创建时间戳。模型以m:n关系连接。 Django关注门后的其他一切。

现在您可以创建序列化程序:

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)

PrimaryKeyRelatedField将获取相关数据。

我没有测试代码并按照我的记忆编写它,但我认为它应该开箱即用。我希望答案可以帮助您,让您了解如何更好地解决问题。