我正在使用django创建一个没有restframework的API。 我有通过POST请求添加数据的问题。添加了所有数据,但外键是联系号码 ,它可以添加一个或多个联系号码
views.py
@method_decorator(csrf_exempt)
def phonebook_list(request):
if request.method == 'GET':
phonebooklist = PhoneBook.objects.all()
serialized_data = [pb.to_json() for pb in phonebooklist]
return JsonResponse(serialized_data, safe=False)
elif request.method == 'POST':
data= request.body.decode('utf8')
data= json.loads(data)
try:
new_contact=PhoneBook(name=data["name"],
address=data["address"],
email=data["email"],
note=data["note"])
new_contact.save()
new_contact_number=ContactNumber(
contact_number=data["contact_number"], #No Contact Numbers Added # It should add one or more contact numbers
number_id=data[PhoneBook.id] #It should add the contact number/s to the contact name added together
)
contact_number.save()
return JsonResponse({"created": data}, safe= False)
except:
return JsonResponse({"error":"not valid data"}, safe=False)
models.py
class PhoneBook(models.Model):
name = models.CharField(max_length=50)
address = models.CharField(max_length=100, default='address')
email = models.CharField(max_length=50, default='email')
note = models.CharField(max_length=100, default='note')
def to_json(self):
contact_numbers = [c.contact_number
for c in self.contact_numbers.all()]
return {
'name': self.name,
'email': self.email,
'address': self.address,
'note': self.note,
'contact_numbers': contact_numbers
}
def __str__(self):
return self.name
class ContactNumber(models.Model):
number = models.ForeignKey(PhoneBook, related_name="contact_numbers")
contact_number= models.CharField(max_length=30)
def __str__(self):
return self.contact_number
这是我添加一些数据后邮递员的结果 第一个是正确的数据,第二个是我输入的错误数据 Image result here
数据库表: contactnumber表: http://prntscr.com/jofv8h 电话簿表: http://prntscr.com/jofvt6
答案 0 :(得分:0)
你最好学习如何在Django中保存ForeignKey,这个例子对你有帮助。 https://docs.djangoproject.com/en/2.0/topics/db/examples/many_to_one/
您可以了解django如何处理模型中的默认ID https://docs.djangoproject.com/en/2.0/topics/db/models/#automatic-primary-key-fields
在您的情况下,ForeignKey列为number
,保存您刚刚创建的新合约对象,而不是保存ID
new_contact_number=ContactNumber(
contact_number=data["contact_number"],
number=new_contact)
new_contact_number.save()
答案 1 :(得分:0)
试试这个答案,
@method_decorator(csrf_exempt)
def phonebook_list(request):
#your code
elif request.method == 'POST':
data = request.body.decode('utf8')
data = json.loads(data)
try:
new_contact = PhoneBook.objects.create(name=data["name"],address=data["address"],email=data["email"],note=data["note"])
ContactNumber.objects.create(contact_number=data["contact_number"],number=new_contact)
serialized_data = [new_contact.to_json()]
return JsonResponse({"created": serialized_data}, safe=False)
except:
return JsonResponse({"error": "not valid data"}, safe=False)
的 UPDATE-1 强>
如下更改您的观点,
def phonebook_list(request):
if request.method == 'GET':
phonebooklist = PhoneBook.objects.all()
serialized_data = [pb.to_json() for pb in phonebooklist]
return JsonResponse(serialized_data, safe=False)
elif request.method == 'POST':
data = request.body.decode('utf8')
data = json.loads(data)
try:
new_contact = PhoneBook.objects.create(name=data["name"], address=data["address"], email=data["email"], note=data["note"])
for number in data["contact_numbers"]:
ContactNumber.objects.create(contact_number=number, number=new_contact)
serialized_data = [new_contact.to_json()]
return JsonResponse({"created": serialized_data}, safe=False)
except:
return JsonResponse({"error": "not valid data"}, safe=False)
那么POST payload
将是这样的,
{
"name": "George",
"email": "zxc1@gmail.com",
"address": "address-32",
"note": "note-77",
"contact_numbers": [
"11",
"22",
"33",
"44"
]
}
通过这种格式,您可以一次添加n
个phone number
个
视图响应类似于
[
{
"name": "Jerin",
"email": "email1@gmail.com",
"address": "address-1",
"note": "note-1",
"contact_numbers": [
"123654",
"136285452"
]
},
{
"name": "Peter",
"email": "email@gmail.com",
"address": "address-2",
"note": "note11",
"contact_numbers": [
"789654"
]
},
{
"name": "George",
"email": "zxc1@gmail.com",
"address": "address-32",
"note": "note-77",
"contact_numbers": [
"11",
"22",
"33",
"44"
]
}
]