我一直在尝试为Model创建一个序列化程序,其中一个字段是ManytoManyField,通过一个添加更多字段的Model。问题是中间序列化程序无法识别已添加字段。为什么我会做错?
这是我的代码:
models.py:
class Product(models.Model):
name = models.CharField(max_length=30, unique=True)
class Movement(models.Model):
date = models.DateTimeField(auto_now_add=True)
products = models.ManyToManyField(Product, through='Movement_Product')
class Movement_Product(models.Model):
movement = models.ForeignKey(Movement)
product = models.ForeignKey(Product)
amount = models.IntegerField()
price = models.DecimalField(max_digits=9, decimal_places=2)
class Input(Movement):
invoice_number = models.CharField(max_length=30, null=True)
serializers.py:
class ProductSerializer(serializers.ModelSerializer):
class Meta:
model = Product
class MovementProductSerializer(serializers.ModelSerializer):
product = ProductSerializer()
price = serializers.DecimalField(max_digits=9, decimal_places=2)
amount = serializers.IntegerField()
class Meta:
model = Movement_Product
class InputSerializer(serializers.ModelSerializer):
date = serializers.DateTimeField()
products = MovementProductSerializer(many=True)
class Meta:
model = Input
views.py:
class InputViewSet(viewsets.ModelViewSet):
queryset = Input.objects.order_by('-date')
serializer_class = InputSerializer
urls.py:
router = routers.DefaultRouter()
router.register(r'input', views.InputViewSet)
urlpatterns = [
url(r'^api/', include(router.urls)),
url(r'^admin/', admin.site.urls),
]
我尝试在浏览器http://127.0.0.1:8000/api/input/中的URL路径上呈现InputSerializer时遇到的错误:
/ api / input /
的属性错误尝试在序列化程序
product
上获取字段MovementProductSerializer
的值时出现AttributeError。序列化程序字段可能名称不正确,与
Product
实例上的任何属性或键都不匹配。原始异常文本是:'Product'对象没有属性'product'。
答案 0 :(得分:1)
试试这个:
class Movement(models.Model):
date = models.DateTimeField(auto_now_add=True)
products = models.ManyToManyField(Product, through='Movement_Product')
@property
def movement_product(self):
return Movement_Product.objects.filter(movement=self)
class InputSerializer(serializers.ModelSerializer):
date = serializers.DateTimeField()
products = serializers.ListField(child=MovementProductSerializer(), source='movement_product')
class Meta:
model = Input