Django REST Framework序列化器-访问现有外键 [英] Django REST Framework serializer - access existing foreign key

查看:126
本文介绍了Django REST Framework序列化器-访问现有外键的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在我的应用中使用 Django Rest Framework ,并且我需要创建包含外键的新模型实例。这些对象引用另一个表中的现有对象,因此我不希望创建这些异物的新实例。我也无法通过它们的主键访问这些对象,因为没有提交信息(我需要过滤 包含在 POST 请求)。

I am using Django Rest Framework in my app, and I need to create new model instances which contain foreign keys. These refer to existing objects in another table, so I don't want new instances of these foreign objects to be created. Also I cannot access these objects via their primary keys, as that information is not submitted (I need to filter on certain fields which are included in the POST request).

我该怎么做? 这个问题似乎解决了同一问题,尽管目前尚不清楚我接受的答案实际上可以解决问题。假设我有两个模型,分别是 Category Item ,并带有 ForeignKey 字段指定类别:

How do I do this? This question seems to address the same issue, though it's not clear to me that the accepted answer actually solves the problem. Suppose I have two models, Category and Item, with a ForeignKey field in the latter specifying the category:

class Category(models.Model):
    name = models.TextField()
    format = models.TextField()
    page = models.IntegerField(default=1)
    order = models.IntegerField(default=1)

class Item(models.Model):
    username = models.TextField()
    title = models.TextField()
    category = models.ForeignKey('Category', null=True)
    data = JSONField(null=True, blank=True)

<$ c的正文$ c> POST 请求由一个JSON有效负载组成,类别定义为指定格式,页面和顺序字段的对象:

The body of the POST request consists of a JSON payload, with the category defined as an object specifying the format, page and order fields:

POST /api/items
{
  "username" : "test",
  "title" : "foo",
  "category" : {
    "format" : "A",
    "page" : 2,
    "order" : 1
  },
  "data" : [1,2,3,4,5]
}

那么我想我可能如下定义我的 Item 序列化程序,覆盖 create ,以便它检索正确的 Category 实例,方法是过滤适当的字段,并将其设置为返回的 Item 实例:

Then I suppose I might define my Item serializer as follows, overriding create so that it retrieves the right Category instance by filtering on the appropriate fields, and setting it into the returned Item instance:

class ItemSerializer(serializers.ModelSerializer):
    category = CategorySerializer()
    data = serializers.ListField()

    class Meta:
        model = Item
        fields = ('username', 'title', 'category', 'data')

    def create(self, validated_data):
        category_dict = validated_data.pop('category')
        item = Item.objects.create(**validated_data)
        format = category_dict.format
        page = category_dict.page
        order = category_dict.order
        item.category = Category.objects.get(format=format, page=page, order=order)
        return item

这是正确的方法吗?

推荐答案

就像

try:
    category = Category.objects.get(format=format, page=page, order=order)
except Category.DoesNotExist:
    # either make it None or create new category, depends on your requirement
    category = None
    # or create new category
except Category.MultipleObjectsReturned:
    category = category.first() # it depends on your requirement
item.category = category

这篇关于Django REST Framework序列化器-访问现有外键的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆