我能得到它的工作,并已低于更新代码。但现在我的问题是如何编辑iceinfo
中的字段?现在,它以IceInfo object
的形式返回,而不是作为可编辑字段。我只能编辑ice_code
和ice_maker
。
老问题
我想为我们的数据库的API。数据库中的信息被划分为多个表格,所有表格的主键都与“Ice-code
”相同。
我一直在努力,现在一个星期的大部分时间将表结合起来,所以我可以从一个URL(api.something.com/ice/
)能够看到(api.something.com/ice/1
)冰和一个列表就能看到详细视图的冰块融合了所有表格的信息。
似乎无论我尝试什么,我都无法合并表格。
这是我到目前为止的草稿。我希望能够最终从前端更新字段。每张桌子的总行数在70-80k左右,他们有比这里更多的列,但我只是想做一个粗略的工作草案。
#models.py
class IceInfo(models.Model):
ice_name = models.TextField(db_column='Ice name', blank=True, null=True)
updated = models.DateTimeField(db_column='Updated')
ice_code = models.ForeignKey(IceList, related_name='iceinfo', db_column='Ice-code', on_delete=models.CASCADE, primary_key=True)
class Meta:
managed = False
db_table = 'Ice_Info'
class IceList(models.Model):
ice_code = models.IntegerField(primary_key=True, db_column='Ice-code', max_length=10)
ice_maker = models.CharField(db_column='Ice Maker', max_length=255, blank=True, null=True)
updated = models.DateTimeField(db_column='Updated')
class Meta:
managed = False
db_table = 'Ice_List'
def __str__(self):
return self.ice_code
#serializers.py
from rest_framework import serializers
from .models import IceList, IceInfo
class IceInfoSerializer(serializers.ModelSerializer):
class Meta:
model = IceInfo
fields = '__all__'
class IceListSerializer(serializers.ModelSerializer):
iceinfo = IceInfoSerializer(many=True)
class Meta:
model = IceList
fields = ('ice_code', 'ice_maker', 'iceinfo')
#的views.py
from .models import IceInfo, IceList
from .serializers import IceListSerializer
from rest_framework.generics import ListAPIView, RetrieveAPIView, RetrieveUpdateAPIView
from rest_framework.filters import SearchFilter, OrderingFilter
class IceList(ListAPIView):
queryset = IceList.objects.all()
serializer_class = IceListSerializer
filter_backends = [SearchFilter, OrderingFilter]
search_fields = ['ice_code', 'ice_maker', 'ice_name']
个结果
"results": [
{
"ice_code": 1,
"iceinfo": [
{
ice_name": "Ice Name 1"
}
)
"ice_maker": "Ice Maker 1"
},
{
"ice_code": 2,
"iceinfo": [
{
ice_name": "Ice Name 2"
}
)
"ice_maker": "Ice Maker 2"
},
在我看来,你不需要IceListSerializer来对IceInfo的许多实例进行序列化,只需使用many = True即可。为什么你甚至需要IceList? –
谢谢你的回复。你能否用许多= True来详细说明你的意思?Ice_List和Ice_Info表都包含更多列,所以这就是为什么使用IceList和IceInfo的原因。 – Shopro
假设你的目标是序列化IceInfo的许多实例,IceList的目的是什么?或者你在尝试一些不同的东西?如果我是对的,你可以通过将查询集传递给序列化程序,并给出关键字many = True。看到这里: [文档](http://www.django-rest-framework.org/tutorial/1-serialization/#working-with-serializers) –