我有以下django课程:
class Event(models.Model):
calendar = models.ForeignKey(Calendar, related_name='cal_event')
department = models.ForeignKey(Department, related_name='events')
title = models.CharField(max_length=30)
date = models.DateTimeField('event date')
roles = models.ManyToManyField(Role, through='EventRoles')
class Meta:
db_table = "event"
unique_together = ("date", "department")
class EventId(models.Model):
event = models.OneToOneField(Event, primary_key=True, related_name='event_number')
number = models.IntegerField(default=0)
class Meta:
db_table = "event_id"
EventId的django rest序列化程序类如下:
class EventIdS(serializers.ModelSerializer):
class Meta:
model = EventId
现在,每当我尝试保存新的EventId
对象时,代码都会在保存它时失败。例如:
def put(self, request, event_pk, format=None):
# Get an existing event object
event = get_object_or_404(Event, pk=event_pk)
# Get id number from ajax request
event_id = request.data.get('id', None)
if event_id:
db_data = {
'event' : event.id,
'number' : event_id
}
idSerial = EventIdS(event, data=db_data)
if idSerial.is_valid():
eventID = event.event_number
eventID.number = event_id
eventID.save()
代码在eventID.save()
失败,我不知道为什么。每当我打印event_id
时,它都是一个长数字(例如:12L)。我错过了什么?欢迎任何想法。
答案 0 :(得分:1)
您应首先致电.save()
而不是idSerial
,它会返回eventID
更新的实例,然后您可以设置数字属性然后保存。
idSerial = EventIdS(event, data=db_data)
if idSerial.is_valid():
eventID = idSerial.save()
eventID.number = event_id
eventID.save()