我对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)
感谢您的帮助!
答案 0 :(得分:2)
借助@ 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。