django REST结合了json卷曲的2种模型视图形式
我有模特:
class Emp(models.Model):
full_name = models.CharField(max_length=100)
mobile = models.CharField(max_length=10,blank=True,null=True)
email = models.EmailField(blank=True,null=True)
class Enquiry(models.Model):
date = models.DateField(default=timezone.now)
number = models.AutoField(primary_key=True)
products = models.ManyToManyField(Product, related_name="products")
referred_by_emp = models.ForeignKey(
Emp,related_name='ref_emp',
null=True,blank=True,
)
序列化程序类:
class ReferrerSerializer(serializers.ModelSerializer):
class Meta:
model = Emp
fields = (
'full_name','mobile','email',
)
class EnquirySerializer(serializers.ModelSerializer):
class Meta:
model = Enquiry
fields = (
'name','mobile','email',
'products',
'referred_by_emp',
)
我希望在输入查询详情时获得Emp的属性,例如full_name,mobile,email。 2款车型的观点:
class RefViewSet(viewsets.ModelViewSet):
"""
API endpoint that allows Emp instances to be viewed or edited.
"""
model = Emp
queryset = Emp.objects.all()
serializer_class = ReferrerSerializer
class EnquiryViewSet(viewsets.ModelViewSet):
"""
API endpoint that allows Enquiry instances to be viewed or edited.
"""
model = Enquiry
queryset = Enquiry.objects.all()
serializer_class = EnquirySerializer
在django REST API中输入查询详细信息时,我也希望获取Emp的详细信息并提交表单。 细节应该在各自的模型中被捕获。 这怎么能实现? 我是django的REST API的新手,没有找到正确的方法。 Plz指导我用详细的代码来实现这一点。 我试过itertools.chain,但可能没有正确使用它进一步我想调用curl命令为相同.Thanx提前使用django 1.6.5
好吧,这不是我推荐做的事情,但是当它刚刚发生时,我一直在那里。
class ReferrerSerializer(serializers.ModelSerializer):
class Meta:
model = Emp
fields = ('full_name','mobile','email')
class EnquirySerializer(serializers.ModelSerializer):
class Meta:
model = Enquiry
fields = ('name','mobile','email','products',)
# As the fields doesn't already exist you can 'copy' them into the serializer
EnquirySerializer.base_fields["full_name"] = ReferrerSerializer().fields["full_name"]
# Then in the view we can create another model instance.
# you should use the Serializer or a Form class and not save the data directly to a Emp instance here but i left that out for clarity.
class SomeViewSet(ModelViewSet):
model = Enquiry
# post() should only handle new/create calls, but if you want it more clear you can override create() instead.
def post(self, request, *args, **kwargs):
self.emp_data = {}
self.emp_data["full_name"] = self.request.DATA.pop("full_name")
return super(SomeViewSet, self).post(request, *args, **kwargs)
def pre_save(self, obj):
emp = Emp.objects.create(**self.emp_data)
obj.referred_by_emp = emp
return obj
链接地址: http://www.djcxy.com/p/48779.html
上一篇: django REST combining 2 model views form for json curl
下一篇: Upload image with ng