django many-de-serialization add


# Add Student
class Addstu1 (APIView):
DEF POST (Self, Request):
Data = request.data
Data [ 'IMG'] = '123456' # IMG data written directly to the dead
Print (Data)
SS = Stuerializers1 (Data = Data)
IF ss.is_valid ():
ss.save ()
return the Response ({ 'code': 200 is, 'Message': 'added successfully'})
return the Response ({ 'code': 10020, 'Message': 'Add failed '})


the most important portion of the sequence

# Add-many student 
class Stuerializers1 (serializers.Serializer):
name = serializers.CharField (MAX_LENGTH = 32)
IMG = serializers.CharField (MAX_LENGTH = 255)
CID = serializers.ListField () # can be added to the ListField plurality
def create ( Self, the Data):
cid = data.pop ( 'cid') #cid not my stu in the field so pop cid
        ss = Stu.objects.create (** data) # Add stu table 
ss.duo.set (cid) # stu add foreign key Dou
return SS

Model
# Course 
class Kc (Base, models.Model):
name = models.CharField (MAX_LENGTH = 32)
. Price = models.DecimalField (= max_digits. 9, decimal_places = 2)
# = sss_set

class Meta -:
named db_table, = 'KC'

# Student table
Stu class (Base, models.Model):
name = models.CharField (max_length = 32)
img = models.CharField (max_length = 255)
# the related_name = 'sss' name when the add-back from the individual when he is equivalent courses the foreign key table sss_set
# can directly replace stu list of dou
Duo = models.ManyToManyField (to = 'Kc', the related_name = 'sss') #
class Meta:
db_table = 'stu'

there is an error, please indicate




Guess you like

Origin www.cnblogs.com/pp8080/p/11828629.html