在Django的非托管模型中模拟Oracle主键

时间:2019-07-17 10:15:48

标签: python django oracle django-rest-framework

我正在处理一个旧项目(Django 1.7,DRF 2.0和Oracle 11.2),我希望REST API检索并填充一个预先定义的Oracle表,该表已定义为该模型:

class ParametriZgodovina(models.Model):

    amp_sif = models.CharField(max_length=5, blank=True)
    kolicina = models.CharField(max_length=20, blank=True)
    datum_od = models.DateField(blank=True, null=True)
    id_np = models.FloatField(blank=True, null=True)
    opomba = models.CharField(max_length=1000, blank=True)
    opomba_user_id = models.FloatField(blank=True, null=True)
    opomba_datetime = models.DateField(blank=True, null=True)

    class Meta:
        managed = False
        db_table = 'parametri_zgodovina'

在获取DatabaseError: ORA-00904: "PARAMETRI_ZGODOVINA"."ID" invalid identifier时,我在模型定义中插入了另一个字段:

rowid = models.CharField(max_length=20, primary_key=True)

这使我能够检索甚至修改数据,但是通过.restore_object()插入新实例失败,并显示DatabaseError: ORA-01733: virtual column not allowed here

此外,当尝试使用print(instance.values())在View的get()方法中显式打印模型实例时,我得到了DatabaseError: ORA-01446: cannot select ROWID from, or sample, a view with DISTINCT, GROUP BY, etc.

我的视图如下:

class ParametriZgodovinaView(APIView):

    def get(self, request):
        events = ParametriZgodovina.objects.all().order_by('amp_sif', 'kolicina','datum_od')

        serializer = ParametriZgodovinaSerializer(events, many=True)

        if serializer.is_valid():
            return Response(serializer.data, status=status.HTTP_200_OK)
        else:
            return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)


    def post(self, request):

        serializer = ParametriZgodovinaSerializer(data=request.DATA, context={'request': request})

        if serializer.is_valid():

            serializer.save()

            return Response(serializer.data, status=status.HTTP_201_CREATED)

        return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)

我的序列化器是:

class ParametriZgodovinaSerializer(serializers.ModelSerializer):

    class Meta:
        model = ParametriZgodovina
        fields = ('amp_sif', 'kolicina', 'id_np', 'opomba', "opomba_datetime")

    def restore_object(self, attrs, instance=None):

        instance = ParametriZgodovina(
            amp_sif = attrs["amp_sif"],
            kolicina = attrs["kolicina"],
            id_np = attrs["id_np"],
            opomba = attrs["opomba"],
            opomba_user_id = self.context['request'].user.id,
            opomba_datetime = datetime.utcnow() + timedelta(hours=1),
            datum_od = datetime.utcnow() + timedelta(hours=1)
        )

        instance.save()

        return instance

问题:如何在Django模型中正确模拟Oracle的入门密钥,以便在不受管理的Oracle表上充分利用Django的ORM?

我最近找到解决方案的地方是this线程,但是扩展CharField类对我来说似乎是个棘手的解决方案...

0 个答案:

没有答案