django 如何在没有产品字段的情况下为该类别模型创建序列化程序?DRF

euoag5mw  于 2023-04-22  发布在  Go
关注(0)|答案(1)|浏览(90)

我想为模型类别创建一个Apiview,并定义一个端点,只执行一个创建类别字段,但Products和Category与ForeignKey方法相关。所以,我正在尝试这种方法,但还没有任何工作。这些是我的模型:

class Category(models.Model):

    name = models.CharField(max_length=255)
    slug = models.SlugField(blank=True) 

    class Meta:
    
        ordering = ('name',) 

    def __str__(self):
        return self.name  
    
    def get_absolute_url(self):
        return f'/{self.slug}/' 

class Product(models.Model):

    category = models.ForeignKey(Category, related_name='products', on_delete=models.CASCADE) # Cascade deletes. Django emulates the behavior of the SQL constraint ON DELETE CASCADE and also deletes the object containing the ForeignKey.
    name = models.CharField(max_length=255)
    slug = models.SlugField()
    description = models.TextField(blank=True, null=True)
    price = models.DecimalField(max_digits=15, decimal_places=2, default=99.99)
    image = models.ImageField(upload_to='uploads/', blank=True)        
    thumbnail = models.ImageField(upload_to='uploads/', blank=True)
    date_added = models.DateTimeField(auto_now_add=True)

    class Meta:
        
        ordering = ('-date_added',) # date create it in descending order

    def __str__(self):

        return self.name

我为产品模型创建了一个序列化程序,它只用于创建产品。

class ProductSerializer(serializers.ModelSerializer):
    url = serializers.HyperlinkedIdentityField(
            view_name='product-detail',
            lookup_field='pk'
    )
    class Meta:

        model = Product
        fields = (
            "category",
            "url", 
            "pk",
            "name",
            "description",
            "price",
            "get_image",
            "get_thumbnail",
            "date_added",
        )
class CategorySerializer(serializers.ModelSerializer):
    
    products = ProductSerializer(many=True)
    
    class Meta:
        model = Category
        fields = ( 
            "id",
            "name",
            "get_absolute_url",
            "products",
        )

另外,我尝试了这个方法,它覆盖了相关字段的create方法;

class CategorySerializer(serializers.ModelSerializer):
    
    products = ProductSerializer(serializers.PrimaryKeyRelatedField(
    many=True, queryset=Product.objects.all())
)
    class Meta:
        
        model = Category
        fields = [
            "name",
            "slug",
            "products"
            ]
        
    def create(self, validated_data):
        products_data = validated_data.pop('products')
        category = Category.objects.create(**validated_data)
        Product.objects.create(category=category, **products_data)
        return Category

    def to_representation(self, category):
        representation = super(CategorySerializer, self).to_representation(category)
        representation['products'] = ProductSerializer(category.product_set.all(), many=True).data
        return representation

给予me this bug = Category()得到了意外的关键字参数:’用户
我可以从管理网站创建类别只。

mefy6pfw

mefy6pfw1#

您可以在序列化程序上设置products不是required
serializers.py

class CategorySerializer(serializers.ModelSerializer):
    products = ProductSerializer(many=True, required=False)
    
    class Meta:
        model = Category
        fields = ( 
            "id",
            "name",
            "get_absolute_url",
            "products",
        )

如果你想定义一个endpoint只用于创建类别,那么你可以使用一个简单的CreateAPIView
views.py

class CategoryCreateAPIView(generics.CreateAPIView):
    queryset = Category.objects.all()
    serializer_class = CategorySerializer

注册URL,比如说:
urls.py

urlpatterns = [
    path('products/create/', CategoryCreateAPIView.as_view())
]

终点

http://localhost:8000/products/create/

特别说明:

1.你可以使用Django的.slugify来覆盖你的模型.create方法来自动填充你的slug字段。
1.同样,也可以从上传的图像创建缩略图。因此,您不需要上传两个文件。

相关问题