2017-03-15 31 views
0

我一直在試圖通過添加更多字段的模型來創建一個模型的序列化程序,其中一個字段是ManytoManyField。問題是中間序列化程序不能識別已添加字段。爲什麼我會做錯?Django在使用中間模型時序列化程序出現屬性錯誤

這裏是我的代碼:

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), 
] 

我,當我嘗試呈現InputSerializer URL路徑在我的瀏覽器http://127.0.0.1:8000/api/input/錯誤:

Attribute Error at /api/input/ 
Got AttributeError when attempting to get a value for field `product` on serializer `MovementProductSerializer`. 
The serializer field might be named incorrectly and not match any attribute or key on the `Product` instance. 
Original exception text was: 'Product' object has no attribute 'product'. 
+0

郵政urls.py,也要求其參數你正在通過。 –

+0

完成。我沒有傳遞任何參數,它只是一個GET到/ api/input /,也只有當輸入模型中有數據時纔會失敗。 –

回答

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 
+0

它說'ManyRelatedManager'對象是不可迭代的 –

+0

在類運動 – Guinner

+0

中加入一個參數'through_fields =('movement','product')'到'products = models.ManyToManyField(Product,through ='Movement_Product')'你的意思是像這樣:'products = models.ManyToManyField(Product,through ='Movement_Product',through_fields =('movement','product'))'仍然一樣:( –

相關問題