将ID存储在子模型的父模型中,这些模型当前通过ForeignKeys相关

时间:2017-09-05 16:10:12

标签: django django-models django-rest-framework

我有三个模型,目前我正在使用这样的网址来做更新并获取内容:

  

http://localhost:8000/manuscripts-api/manuscriptlibrary/28/

我的问题与我应该使用的方法有关,因此我可以在我的ManuscriptItem模型中包含相关库和设置的ID 。我可以将哪些字段添加到ManuscriptItem模型中?

我的模特:

class ManuscriptItem(models.Model):
    """Represents a single manuscript's content"""

    author = models.ForeignKey('accounts_api.UserProfile', on_delete=models.CASCADE)
    title = models.CharField(max_length=255, blank=True)
    content = models.CharField(max_length=99999999, blank=True)

    def __str__(self):
        """Django uses when it needs to convert the object to a string"""
        return str(self.id)


class ManuscriptLibrary(models.Model):
    """Represents a single manuscript's library"""

    manuscript = models.OneToOneField(ManuscriptItem, on_delete=models.CASCADE)
    bookmarks = models.CharField(max_length=99999999)
    history = models.CharField(max_length=99999999)

    def __str__(self):
        """Django uses when it needs to convert the object to a string"""
        return str(self.manuscript)


class ManuscriptSettings(models.Model):
    """Represents a single manuscript's settings"""

    manuscript = models.OneToOneField(ManuscriptItem, on_delete=models.CASCADE)
    citation_suggestions = models.BooleanField(default=False)
    terminology_suggestions = models.BooleanField(default=False)
    paper_suggestions = models.BooleanField(default=False)

    def __str__(self):
        """Django uses when it needs to convert the object to a string"""
        return str(self.manuscript)

我的序列化器:

class ManuscriptItemSerializer(serializers.ModelSerializer):
    """A serializer for manuscript items."""

    class Meta:
        model = models.ManuscriptItem
        fields = ('id', 'author', 'title', 'content')
        extra_kwargs = {'author': {'read_only': True}}


class ManuscriptLibrarySerializer(serializers.ModelSerializer):
    """A serializer for a manuscript's library."""

    class Meta:
        model = models.ManuscriptLibrary
        fields = ('id', 'manuscript', 'bookmarks', 'history')


class ManuscriptSettingsSerializer(serializers.ModelSerializer):
    """A serializer for a manuscript's settings."""

    class Meta:
        model = models.ManuscriptSettings
        fields = ('id', 'manuscript', 'citation_suggestions', 'terminology_suggestions', 'paper_suggestions')

2 个答案:

答案 0 :(得分:3)

您不一定需要向ManuscriptItem模型添加任何新字段。您可以通过定义外键的related_name属性来访问相关ManuscriptLibrary和ManuscriptSettings对象的id。

class ManuscriptLibrary(models.Model):
    manuscript = models.OneToOneField(ManuscriptItem, on_delete=models.CASCADE, related_name='library')


class ManuscriptSettings(models.Model):
    manuscript = models.OneToOneField(ManuscriptItem, on_delete=models.CASCADE, related_name='setting')

迁移后,您可以使用manuscript_item.library访问相关的库对象,使用manuscript_item.setting访问相关设置。访问ID可以通过manuscript_item.library.id完成。

编辑:要显示序列化对象中的ID,您可以修改ManuscriptItemSerializer,如下所示

class ManuscriptItemSerializer(serializers.ModelSerializer):
    library = ManuscriptLibrarySerializer(required=False)
    setting = ManuscriptSettingsSerializer(required=False)

    class Meta:
        model = models.ManuscriptItem
        fields = ('id', 'author', 'title', 'content', 'library', 'setting', )

答案 1 :(得分:1)

由文档one_to_one

组成

您的ManuscriptItem实例有两个属性manuscriptlibrary - ManuscriptLibrary模型的实例和manuscriptsettings模型的ManuscriptSettings实例。因此,您可以通过manuscriptlibrary.pkmanuscriptsettings.pk获取ID,但可能是提高可读性的最佳解决方案,您可以使用related_name作为arjun27写入。