我有以下型号。
Models.py
from django.db import models
from rest_framework.validators import UniqueValidator
import datetime
# Create your models here.
class Member(models.Model):
uin = models.CharField(max_length=9)
name = models.CharField(max_length = 15)
cardNumber = models.CharField(max_length=55,blank=True)
points = models.IntegerField()
class Meta:
ordering = ['uin']
def __str__(self):
return self.uin
class Event(models.Model):
eventName = models.CharField(max_length=60,blank=True)
points = models.IntegerField(default = 0)
date = models.DateField( default=datetime.date.today)
members = models.ManyToManyField(Member)
class Meta:
ordering = ['eventName']
def __str__(self):
return self.eventName
以及以下序列化器
class MemberSerializer(serializers.ModelSerializer):
class Meta:
model = Member
# validators = UniqueValidator(queryset=)
fields = ['name','uin','points','cardNumber']
# overloading to_representation for if you want to add new datafields
def to_representation(self, instance):
data = super().to_representation(instance)
return data
class EventSerializer(serializers.ModelSerializer):
class Meta:
model = Event
fields = ['id','eventName','date', 'members','points']
# overloading to_representation for if you want to add new datafields
def to_representation(self, instance):
data = super().to_representation(instance)
return data
在新的端点上,我希望用户提供事件ID和卡号。给定这些参数,我希望api将这个成员添加到事件中。
我已经能够使用django shell进行以下操作:
givenId = 1
givenCardNumber = '123439483'
# select desired event
selectedEvent = Event.objects.filter(id=givenId)
selectedMember = Member.objects.filter(cardNumber=givenCardNumber)
selectedEvent.members.add(selectedMember)
但是,我希望能够使用api做到这一点。