Can';t在Django中添加外键
我正在使用django制作一个不带restframework的API。 我无法通过POST请求添加数据。添加所有数据,但外键除外,外键是联系人号码它可以添加一个或多个联系人号码 视图.pyCan';t在Django中添加外键,django,python-3.x,api,Django,Python 3.x,Api,我正在使用django制作一个不带restframework的API。 我无法通过POST请求添加数据。添加所有数据,但外键除外,外键是联系人号码它可以添加一个或多个联系人号码 视图.py @method_decorator(csrf_exempt) def phonebook_list(request): if request.method == 'GET': phonebooklist = PhoneBook.objects.all() serial
@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)
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
型号.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)
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
这是我在postman中添加了一些数据后得出的结果
第一个是正确的数据,第二个是我输入的错误数据
数据库表:
联系人号码表:
电话簿表:
您最好学习如何在Django中保存外键,此示例将对您有所帮助。 您还可以了解django如何处理模型中的默认id 在您的情况下,ForeignKey列是
number
,保存您刚刚创建的新合同对象,而不是保存id
new_contact_number=ContactNumber(
contact_number=data["contact_number"],
number=new_contact)
new_contact_number.save()
试试这个答案,@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)
更新-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有效负载将如下所示,
{
"name": "George",
"email": "zxc1@gmail.com",
"address": "address-32",
"note": "note-77",
"contact_numbers": [
"11",
"22",
"33",
"44"
]
}
通过此格式,您可以一次添加电话号码的号码。n
视图响应可能类似于
[
{
"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"
]
}
]
对象中是否只有联系人号码?还是联系人的身份证?正如我在上面介绍的数据库表中所示。@ajiejot django将帮助您自动创建contact.id,因此您不必关心它,除非您需要设置特殊的id列。现在,我忘了在contact_number=data[“contact_number”]上添加字母s
。非常感谢你。但是我使用添加新创建联系人的新id。联系人号码仍然是空的,我在ContactNumber.objects.create的行下放置了print,但没有响应,因此在ContactNumber上创建对象可能有错误。现在可以工作了,我忘了在ContactNumber=数据[“contact\U number”]上添加字母s
。非常感谢你。但是我的联系电话格式不对。这很奇怪,看看联系人号码列表{“name”:“Alvin”,“email”:qwe@gmail.com“,”地址“:”Col“,”备注“:”noting“,”contact_number“:[”[“['123456','1234567']]”]}
但是当我手动添加到管理页面时,完全没有问题。。。我不明白问题出在哪里。。C