Django REST Framework在serializer中创建外键对象

时间:2018-05-09 13:37:01

标签: django python-3.x django-rest-framework

您好我是REST Framework的新手。我正在尝试让我的序列化器创建新城镇,如果它在我创建新商店时不存在。

class ShopSerializer(serializers.HyperlinkedModelSerializer):

    town = serializers.SlugRelatedField(slug_field='town', queryset=Town.objects.all())
    # town_send = serializers.CharField(max_length=50, write_only='True')

    class Meta:
        model = Shop
        fields = ('name', 'address', 'opening_hour', 'closing_hour', 'owner', 'geo_point', 'town', 'url')
        read_only_fields = ('owner',)


    def create(self, validated_data):
        request = self.context['request']
        owner = request.user
        town = validated_data.pop('town')
        town, exist = Town.objects.get_or_create(town=town)
        shop = Shop.objects.create(owner=owner, town=town, **validated_data)
        return shop

目前,如果我发送现有的城镇名称,它会更新,但是当我给它新城镇时,它会显示:“带有场镇= x的对象不存在”

编辑:

型号:

class Shop(models.Model):
    name = models.CharField(verbose_name='name', max_length=100)
    town = models.ForeignKey('Town', verbose_name='town', on_delete=models.CASCADE, related_name='shops')
    address = models.CharField(verbose_name='address', max_length=100)
    opening_hour = models.TimeField(verbose_name='opening')
    closing_hour = models.TimeField(verbose_name='closing')
    photo = models.ImageField(verbose_name='photo', upload_to='photos', blank=True)
    geo_point = PointField(verbose_name='coordinates')
    owner = models.ForeignKey(User, on_delete=models.CASCADE, verbose_name='owner', related_name='shops')
    created = models.DateTimeField(auto_now_add=True, verbose_name='creation date')
    modified = models.DateTimeField(auto_now=True, verbose_name='modification date')

    def __str__(self):
        return self.name

class Town(models.Model):
    town = models.CharField(verbose_name='town', max_length=50, unique=True)

    def __str__(self):
        return self.town

视图集:

class ShopViewSet(viewsets.ModelViewSet):
    """
    API endpoint that allows shops to be viewed, created or edited.
    """
    queryset = Shop.objects.all().order_by('-created')
    serializer_class = ShopSerializer
    permission_classes = [IsAuthenticatedOrReadOnly]

回溯只是

[2018-05-09 15:12:22 +0000] [8] [DEBUG] GET /api/Shops/
[2018-05-09 15:13:13 +0000] [8] [DEBUG] POST /api/Shops/

错误仅在REST API窗口中以json显示,上面显示错误文本

0 个答案:

没有答案