我的意图是每次将短信发送到我的服务器时,服务器应通过数据库查看sms中的数字是否已经是存储对象,如果不是则创建并将对象保存到数据库中我做错了吗?
views.py
from django.http import request
from django_twilio.decorators import twilio_view
from django_twilio.request import decompose
from twilio.twiml.messaging_response import MessagingResponse
from .models import Contacts
@twilio_view
def sms_choice(request):
twilio_request = decompose(request)
contact_num = twilio_request.from_
contact_info = ['Thanks for your subscription',
"How old are you?", "Annual Income?"]
response = twilio_request.body
resp = MessagingResponse()
subscribers = [Contacts.objects.all()]
for contact in subscribers:
if contact_num != contact.customer_number:
b = Contacts(customer_number=contact_num)
b.save()
resp.message(contact_info[0])
elif contact_num == contact.customer_number:
resp.message(contact_info[1])
print(contact_num, response)
return str(resp)
models.py
from django.db import models
class Contacts (models.Model):
customer_number = models.CharField(max_length=15)
customer_age = models.CharField(max_length=4,
null=True)
customer_income = models.CharField(max_length=10,
null=True)
def __unicode__(self):
return self.customer_number
答案 0 :(得分:1)
您似乎有两种情况:在第一种情况下,您的数据库中不存在联系号码,因此您要回复消息1;在第二种情况下,联系号码确实存在,因此您要回复消息2。
因此,您应该检查是否有该号码的记录,如果没有,请创建它。确切地说有一个快捷方式:get_or_create
。
resp = MessagingResponse()
contact, created = Contacts.objects.get_or_create(customer_number=contact_num)
if created:
resp.message(contact_info[0])
else:
resp.message(contact_info[1])
# I presume you want to update the customer age here
contact.age = response
contact.save()
return resp