简体   繁体   中英

How to create view and serializer to add to many to many field in DRF

I implemented two models, Card and Dish. I used many-to-many relationship because Dish can be in many cards. 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? 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 .

for example in your CreateView just after the serializer add this:

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM