django POST在2个模型/数据库表中

时间:2017-03-02 14:08:50

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

我绝对是新手,刚刚完成了我的需求教程。现在我卡住了,因为我想同时保存2个模型中的POST订单的所有数据。我试过这个def create(self, valiated_data):,但Altkunde表仍然是空的,而我在Kunde模型中有很多新条目。

经过数小时的研究,我无法找到解决方案。

请提供任何提示或提示。

这是 models.py

class Kunde(models.Model):
   QR = models.CharField(max_length=3, default='', primary_key=True)
   created = models.DateTimeField(blank=True, auto_now_add=True)
   Name = models.CharField(max_length=50, blank=True, default='')
   Info = models.TextField(max_length=200, blank=True, default='')
   owner = models.ForeignKey('auth.User', related_name='kunden', on_delete=models.CASCADE)

   class Meta:
        ordering = ('created',)


class AltKunde(models.Model):
   QR = models.CharField(max_length=3, default='', primary_key=True)
   created = models.DateTimeField(blank=True, auto_now_add=True)
   Name = models.CharField(max_length=50, blank=True, default='')
   Info = models.TextField(max_length=200, blank=True, default='')
   Verleiher = models.OneToOneField(User, 'username')

   class Meta:
      ordering = ('created',)

views.py

class KundeViewSet(viewsets.ModelViewSet):
    queryset = Kunde.objects.all()
    serializer_class = KundeSerializer
    permission_classes = [IsAdminUser]

    def perform_create(self, serializer):
        serializer.save(owner=self.request.user)


class AltKundeView(viewsets.ReadOnlyModelViewSet):
    queryset = AltKunde.objects.all()
    serializer_class = AltkundeSerializer

serializer.py

class KundeSerializer(serializers.HyperlinkedModelSerializer):
    owner = serializers.ReadOnlyField(source='owner.username')

    class Meta:
        model = Kunde   #Kunden die Notebook leihen
        fields = ('url', 'QR', 'owner', 'created', 'Name', 'Info')

    def create(self, validated_data):
        Altkundeeintrag = AltKunde.objects.create(**validated_data)
        return Kunde.objects.create(**validated_data)

class AltkundeSerializer(serializers.HyperlinkedModelSerializer):

    class Meta:
        model = AltKunde   #Kunden die Notebook geliehen haben (Altbestand)
        fields = ('url', 'QR', 'Verleiher' 'created', 'Name', 'Info')

1 个答案:

答案 0 :(得分:1)

models.py中你可以这样做:

from django.dispatch import receiver
from django.db.models.signals import post_save

class Kunde(AbstractKunde):
    ...

class AltKunde(AbstractKunde):
    ...

@receiver(post_save, sender=Kunde)
def handle_Kunde_created(sender, instance, *args, **kwargs):
    //kwargs['created'] will return True if a Kunde instance is created.
    if not kwargs.get('created'):
        // I'm not doing anything here, but potentially
        // you can sync object updates here as well
        return

    AltKunde.objects.create(
        QR=instance.QR,
        created=instance.created,
        Name=instance.Name,
        Info=instance.Info,
        Verleiher=instance.Verleiher)

在你的KundeSerializer中,你不必再这样做了:Altkundeeintrag = AltKunde.objects.create(**validated_data)