简体   繁体   English

如何创建视图和序列化程序以添加到 DRF 中的多对多字段

[英]How to create view and serializer to add to many to many field in DRF

I implemented two models, Card and Dish.我实现了两个模型,Card 和 Dish。 I used many-to-many relationship because Dish can be in many cards.我使用了多对多关系,因为 Dish 可以在许多卡片中。 Furthermore, I have been struggling and could not get answer anywhere how to update created card with dish.此外,我一直在苦苦挣扎,无法在任何地方得到答案,如何用菜更新创建的卡片。 Or create a card with dishes in it.或者创建一张卡片,里面有菜肴。 Should I try to create a middle filed with IDs of card and dish or there is some other way to do it in DRF?我应该尝试使用卡片和盘子的 ID 创建一个中间文件,还是在 DRF 中有其他方法可以做到这一点? I have been struggling with this for some time and would greatly appreciate some tip please.我已经为此苦苦挣扎了一段时间,非常感谢一些提示。 Here is the code:这是代码:



class Dish(models.Model):
    name = models.CharField(max_length=255, unique=True)
    description = models.TextField(max_length=1000)
    price = models.DecimalField(max_digits=5, decimal_places=2)
    preparation_time = models.IntegerField()
    date_added = models.DateField(auto_now_add=True)
    update_date = models.DateField(auto_now=True)
    vegan = models.BooleanField(default=False)

    def __str__(self):
        return self.name


class Card(models.Model):
    name = models.CharField(max_length=255, unique=True)
    description = models.TextField(max_length=1000)
    date_added = models.DateField(auto_now_add=True)
    update_date = models.DateField(auto_now=True)
    dishes = models.ManyToManyField(Dish, blank=True)

    def __str__(self):
        return self.name



class DishSerializer(serializers.ModelSerializer):


    class Meta:
        model = Dish
        fields = ['id', 'name', 'description', 'price', 'how_long_to_prepare', 'date_added', 'update_date', 'vegan']
        read_only_fields = ['id']


class CardSerializer(serializers.ModelSerializer):
    class Meta:
        model = Card
        fields = ['id', 'name', 'description', 'date_added', 'update_date', 'dishes']
        read_only_fields = ['id']

class CreateCardView(generics.CreateAPIView):
    """Create a new user in the system."""
    serializer_class = serializers.CardSerializer


class AddToCardView(generics.CreateAPIView):
    serializer_class = serializers.CustomUserSerializer

You can use the method perfom_create .您可以使用perfom_create方法。

for example in your CreateView just after the serializer add this:例如,在序列化程序之后的 CreateView 中添加以下内容:

def perform_create(self, serializer):
    dish = Dish.objects.get(pk=self.kwargs['pk']) 
    serializer.save(dish=dish, author=self.request.user)

From the documentation:从文档中:

For instance, you might set an attribute on the object based on the request user, or based on a URL keyword argument.例如,您可以基于请求用户或基于 URL 关键字参数在 object 上设置属性。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何使用DRF串行器将联结表中的数据添加到多对多字段? - How to add data from junction table to many to many field with DRF serializer? 如何通过 Axios 和 Vue.js 传递数据,在 DRF 序列化程序中为具有多对多字段的模型编写 create() 函数 - How to write a create() function in DRF serializer for a model with a many-to-many field by passing data through Axios, and Vue.js 如何将数据添加到 Django DRF 中的多对多字段 - How to add data to Many-To-Many field in Django DRF DRF 3 - 使用尽管表创建多对多更新/创建序列化程序 - DRF 3 - Creating Many-to-Many update/create serializer with though table 在序列化程序中创建多对多字段数据 - Create many-to-many field data in serializer 如何更新 DRF 中的多对多字段 - How to update a many to many field in DRF DRF 创建仅在序列化程序设置为 (many=True) 时有效 - DRF create only works if serializer is set to (many=True) django/drf:多对多、序列化、重复 - django/drf: many-to-many, serializer, duplicates 在 object 创建上保存多对多字段 - Django DRF - Save many-to-many field on object create - Django DRF Django 多对多运行 2n 查询的 DRF 序列化程序方法字段 - Django DRF serializer method field on many to many running 2n queries
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM