我正在使用Djangorestframework处理传入的Webhook。我必须为模型编写一个视图。我只想检查我是否正确? Refer this for more information
class WebhookTransaction(models.Model):
UNPROCESSED = 1
PROCESSED = 2
ERROR = 3
STATUSES = (
(UNPROCESSED, 'Unprocessed'),
(PROCESSED, 'Processed'),
(ERROR, 'Error'),
)
date_generated = models.DateTimeField()
date_received = models.DateTimeField(default=timezone.now)
body = hstore.SerializedDictionaryField()
request_meta = hstore.SerializedDictionaryField()
status = models.CharField(max_length=250, choices=STATUSES, default=UNPROCESSED)
objects = hstore.HStoreManager()
def __unicode__(self):
return u'{0}'.format(self.date_event_generated)
class Message(models.Model):
date_processed = models.DateTimeField(default=timezone.now)
webhook_transaction = models.OneToOneField(WebhookTransaction)
team_id = models.CharField(max_length=250)
team_domain = models.CharField(max_length=250)
channel_id = models.CharField(max_length=250)
channel_name = models.CharField(max_length=250)
user_id = models.CharField(max_length=250)
user_name = models.CharField(max_length=250)
text = models.TextField()
trigger_word = models.CharField(max_length=250)
def __unicode__(self):
return u'{}'.format(self.user_name)
这是我解决问题的模型。在此之后,我尝试为此编写视图 这是我的代码
def DRSWebhookTransactionView(request):
if request.method == 'GET':
webhooktransaction = WebhookTransaction.objects.all()
serializer = WebhookTransactionSerializer(webhooktransaction, many=True)
return JsonResponse(serializer.data, safe=False)
elif request.method == 'POST':
data = JSONParser().parse(request)
serializer = WebhookTransactionSerializer(data=data)
if serializer.is_valid():
serializer.save()
return JsonResponse(serializer.data, status=201)
return JsonResponse(serializer.errors, status=400)
def DRSMessageView(request):
if request.method == 'GET':
message = Message.objects.all()
serializer = MessageSerializer(snippets, many=True)
return JsonResponse(serializer.data, safe=False)
elif request.method == 'POST':
data = JSONParser().parse(request)
serializer = MessageSerializer(data=data)
if serializer.is_valid():
serializer.save()
return JsonResponse(serializer.data, status=201)
return JsonResponse(serializer.errors, status=400)
我还没有写序列化器部分,只是给出一个想法
class WebhookTransactionSerializer(serializers.ModelSerializer)
class Meta:
model = WebhookTransaction
fields = '_all_'
class MessageSerializer(models.ModelSerializer)
class Meta:
model = Message
fields = '_all_'