我对 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 模型。考虑到“服务”变量是什么,我想将主键传递给另一种模式。前任。 SMS.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
我现在可以按照自己喜欢的方式使用 service 或 proc_id。
关于python - Django Rest Framework : CreateAPIView, 存储数据时我想使用主键,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54930850/