Django REST 框架 - 在序列化器中添加深度导致外键约束在 POST 数据上失败

问题描述 投票:0回答:2

我有一个这样的模型:

class KioskShelfMapping(models.Model):
    mapped_shelf_basket_name_reference = models.ForeignKey(ShelfBasketMapping, on_delete=models.CASCADE, default=1)
    mapped_shelf_name = models.CharField(max_length=15, null=False, blank=False, default="default")
    mapped_kiosk_name = models.CharField(max_length=15, blank=False, null=False, default="default")
    shelf_position = models.PositiveSmallIntegerField(null=False, blank=False, default=0)

下面是我的序列化器:

class KioskShelfMappingSerializer(serializers.ModelSerializer):
    class Meta:
        model = KioskShelfMapping
        fields = ['id', 'mapped_shelf_basket_name_reference', 'mapped_shelf_name', 'mapped_kiosk_name', 'shelf_position']
        depth = 2

我面临的问题是每当我添加向模型发布一些数据的深度时

FOREIGN KEY 约束失败

但是当我删除深度字段时,我能够成功将数据发布到模型。我尝试搜索相同的问题并发现this并相应地修改了我的序列化器:

class KioskShelfMappingSerializer(serializers.ModelSerializer):

    class Meta:
        model = KioskShelfMapping
        fields = ['id', 'mapped_shelf_basket_name_reference', 'mapped_shelf_name', 'mapped_kiosk_name', 'shelf_position']
        depth = 2
    
    def __init__(self, *args, **kwargs):
        super(KioskShelfMappingSerializer, self).__init__(*args, **kwargs)
        request = self.context.get('request')
        if request and request.method =='POST':
            print('Method is POST')
            self.Meta.depth = 0
            print(self.Meta.depth)
        else:
            self.Meta.depth = 2

这似乎不起作用。我仍然遇到同样的错误。我哪里错了?感谢您提前提供帮助。

django django-rest-framework foreign-keys django-serializer
2个回答
0
投票
def __init__(self, *args, **kwargs):
    super(ProductSerializer, self).__init__(*args, **kwargs)
    request = self.context.get('request')
    if request and request.method == 'POST' or request.method == 'PUT' or request.method == 'PATCH':
        print('Method is POST')
        self.Meta.depth = 0
        print(self.Meta.depth)
    else:
        print(f"Method is - {request.method}")
        self.Meta.depth = 2

    def __init__(self, *args, **kwargs):
    super(ProductSerializer, self).__init__(*args, **kwargs)
    request = self.context.get('request')
    self.Meta.depth = 0
    if request and request.method == 'GET':
        self.Meta.depth = 2

0
投票

我也遇到过同样的问题。我知道这不是一个好方法,但它解决了我的问题。 我已经更改了views.py 文件中序列化器的深度。

更改前:

@api_view(['GET', 'POST'])
def movie_detail(request, pk):
    if request.method=='GET':
        movie = get_object_or_404(Movie.objects.select_related('director'), pk=pk)
        serializer = MovieSerializer(movie)
        return Response(serializer.data)
    elif request.method=='POST':
        serializer = MovieSerializer(data=request.data)
        serializer.is_valid(raise_exception=True)
        serializer.save()
        return Response(serializer.data)

而且它无法正常工作。

更改后:

@api_view(['GET', 'POST'])
def movie_detail(request, pk):
    if request.method=='GET':
        movie = get_object_or_404(Movie.objects.select_related('director'), pk=pk)
        serializer = MovieSerializer(movie)
        return Response(serializer.data)
    elif request.method=='POST':
        MovieSerializer.Meta.depth=0 ############### this line is added
        serializer = MovieSerializer(data=request.data)
        serializer.is_valid(raise_exception=True)
        serializer.save()
        MovieSerializer.Meta.depth=1 ###############  this line is added
        return Response(serializer.data)

并且成功了。

*** 注意 ***

如果您不将深度更改回之前的值,它将保持为 0,并且当您使用 GET 方法时,结果不会显示嵌套。

© www.soinside.com 2019 - 2024. All rights reserved.