Skip to main content
 首页 » 编程设计

python之Django rest framework : CreateAPIView, 存储数据时我想用主键

2024年09月03日31虾米姐

我是 django 和 python 的新手,需要一些帮助。目前可以对存储数据的我的应用程序进行 API 调用。但是我需要在存储之后做一些业务逻辑。我该怎么做。

我的看法:

class ProcList(generics.CreateAPIView):  
    queryset = Proc.objects.all() 
    serializer_class = ProcSerializer 
    permission_classes = (IsAdminOrReadOnly,) 
    lookup_url_kwarg = 'proc_id' # primary key 

我的序列化器:

class BlobSerializer(serializers.ModelSerializer): # Child (Old Avatar) 
    key = serializers.CharField() 
    value = serializers.CharField()   
    class Meta: 
        model = Blob 
        fields = ('pk', 'key', 'value') 
 
class ProcSerializer(WritableNestedModelSerializer): # Father (Old profile) 
    blobs = BlobSerializer(many=True)     
    class Meta: 
        model = Proc 
        fields = ( 
            'pk', 
            .... Hidden/removed for length purpuse 
            'service', 
            'country_code', 
            'blobs' 
        ) 

我的模型(只有 Proc-one,因为 Blob 模型不重要)

class Proc(models.Model): # Father (Old profile) 
    MY_SERVICES = ( 
        ("em", 'Email'), 
        ("sm", 'SMS'), 
        .... Hidden/removed for length purpuse 
    ) 
    proc_id = models.AutoField(primary_key=True, help_text="Primary key") 
    service = models.CharField(max_length=2, choices=MY_SERVICES, blank=True, default='mc', help_text='What service is desired, MyChoice is default') 
    .... Hidden/removed for length purpuse 
    country_code = models.CharField(max_length=255) 
    created_at = models.DateTimeField(auto_now=True, name='created_at') 

我想要的结果是 API 调用后像现在一样存储到 Proc 和 Blob 模型。鉴于“服务”变量是什么,我想将主键传递给另一种模式。前任。短信.proc(proc_id)

例子(丑陋,抱歉=)

class ProcList(generics.CreateAPIView):  
    queryset = Proc.objects.all() 
    serializer_class = ProcSerializer 
    permission_classes = (IsAdminOrReadOnly,) 
    lookup_url_kwarg = 'proc_id' # primary key 
 
    queryset.get.service # somehow fetch the service-variable from the record created in Proc-model. 
    queryset.get.proc_id # somehow fetch the primary key from the record created in Proc-model. 
 
   if service == 'sms': 
        Sms.store(proc_id) # Not really important what this looks like. Only how i can get the proc_id and do whatever I want 
   elif service == 'email': 
        Sms.store(proc_id) 

感谢您的帮助!

请您参考如下方法:

感谢@drec4s 我解决了它:

class ProcList(generics.CreateAPIView): # Endast Create för att skapa en proc 
    queryset = Proc.objects.all() 
    serializer_class = ProcSerializer 
    permission_classes = (IsAdminOrReadOnly,) 
    lookup_url_kwarg = 'proc_id' 
 
    def perform_create(self, serializer): 
        q = serializer.save() 
        TmpLogg(entry=q.service).save() # the other variable i need 

我现在可以随心所欲地使用服务或 proc_id。