使用Serialaizer时如何在Django中使用ManyToManyField在第三个table中添加中间ID?
How to add middle IDs in third table with ManyToManyField in Django when using Serialaizer?
我有 table 个这样的:
class Education(models.Model):
title = models.CharField(default=None, max_length=100)
content = models.TextField(default=None)
price = models.ManyToManyField(Price)
class Price(models.Model):
cost = models.CharField(default=None, max_length=20)
然后从客户端得到一个请求并尝试将其保存在 三个tables 中,我对两个 tables [=14] 没问题=] 和 Price
但因为我正在使用 serializer 我不知道如何更新第三个 table(中间)。
def post(self, request):
cost = request.POST.get('cost')
price = Price.objects.create(cost=cost)
education_serializer = EducationSerializer(data=request.data)
if education_serializer.is_valid():
education_serializer.save()
好的,我这里更新了两个table,后面不知道怎么更新第三个table。如果我不使用序列化程序,我可以这样写:
education.price.add(price)
调用education_serializer.save
returns一个Education
的实例,所以可以这样写:
def post(self, request):
cost = request.POST.get('cost')
price = Price.objects.create(cost=cost)
education_serializer = EducationSerializer(data=request.data)
if education_serializer.is_valid():
education = education_serializer.save()
education.price.add(price)
我有 table 个这样的:
class Education(models.Model):
title = models.CharField(default=None, max_length=100)
content = models.TextField(default=None)
price = models.ManyToManyField(Price)
class Price(models.Model):
cost = models.CharField(default=None, max_length=20)
然后从客户端得到一个请求并尝试将其保存在 三个tables 中,我对两个 tables [=14] 没问题=] 和 Price
但因为我正在使用 serializer 我不知道如何更新第三个 table(中间)。
def post(self, request):
cost = request.POST.get('cost')
price = Price.objects.create(cost=cost)
education_serializer = EducationSerializer(data=request.data)
if education_serializer.is_valid():
education_serializer.save()
好的,我这里更新了两个table,后面不知道怎么更新第三个table。如果我不使用序列化程序,我可以这样写:
education.price.add(price)
调用education_serializer.save
returns一个Education
的实例,所以可以这样写:
def post(self, request):
cost = request.POST.get('cost')
price = Price.objects.create(cost=cost)
education_serializer = EducationSerializer(data=request.data)
if education_serializer.is_valid():
education = education_serializer.save()
education.price.add(price)