Django REST框架外键 - 无法从JSON创建对象

时间:2017-06-13 19:22:51

标签: django django-rest-framework

我有以下设置

模型

class Day(models.Model):
  date = models.DateField(auto_now=False, auto_now_add=False)
  price = models.FloatField()
  paymentMethod = models.CharField(max_length = 200)

class Reservation(models.Model):
  start = models.DateField(verbose_name='Заезд', auto_now=False, auto_now_add=False)
  end = models.DateField(verbose_name='Выезд', auto_now=False, auto_now_add=False)
  hasRefund = models.BooleanField(verbose_name='Возвратная бронь', default=True)
  room = models.ForeignKey('Room', verbose_name='Номер', on_delete=models.CASCADE)
  day = models.ManyToManyField(Day, blank=True)
  check_in_time = models.CharField(verbose_name='Время заезда', max_length=200)
  check_out_time = models.CharField(verbose_name='Время выезда', max_length=200)
  guest_name = models.CharField(verbose_name='Имя гостя', max_length=200, blank=True)
  payed = models.BooleanField(verbose_name='Оплачено', default=False)


class Room(models.Model):
  name = models.CharField(max_length = 200, null=True)

视图

class ReservationCreateAPIView(CreateAPIView):
  queryset = Reservation.objects.all()
  serializer_class = ReservationSerializer

串行器

class DaySerializer(serializers.ModelSerializer):
  class Meta:
    model = Day
    fields = [
        'date',
        'price',
        'paymentMethod',
    ]

class RoomSerializer(serializers.ModelSerializer):
  class Meta:
    model = Room
    fields = [
        'pk',
        'name',
    ]

class ReservationSerializer(serializers.ModelSerializer):
   room = RoomSerializer
   day = DaySerializer(many=True)

  class Meta:
    model = Reservation
    fields = [
        'start',
        'end',
        'hasRefund',
        'room',
        'day',
        'check_in_time',
        'check_out_time',
        'guest_name',
        'payed',
    ]

def create(self, validated_data):
    day_data = validated_data.pop('day')
    room_data = validated_data.pop('room')
    reservation = Reservation.objects.create(**validated_data)

    room = Room.objects.get_or_create(name=room_data['name'])
    reservation.room.add(room)

    for day in day_data:
        day, created = Day.objects.get_or_create(date=day['date'], price=day['price'], paymentMethod=day['paymentMethod'])
        reservation.day.add(day)
    return reservatrion

数据,我尝试保存

{
"start": "2017-12-12",
"end": "2017-12-12",
"hasRefund": false,
"room": 2,
"day": [ {
   "date": "2017-12-12",
   "price": "2",
   "paymentMethod": "3"
},
{
    "date": "2017-12-12",
    "price": "2",
    "paymentMethod": "3"
}
],
"check_in_time": "14-00",
"check_out_time": "12-00",
"guest_name": "Ivan",
"payed": false
}

我得到的回应

IntegrityError at /core/create/
NOT NULL constraint failed: core_reservation.room_id

我做错了什么?

1 个答案:

答案 0 :(得分:0)

您尝试创建没有Reservation的{​​{1}}。您的预订模型不允许其房间为空值。

一种方法是首先创建一个房间,然后将其分配给预订:

Room

您也可以简单地在没有房间的情况下进行预订,然后再添加房间。在您的模型中使用:

room_data = validated_data.pop('room')
room = Room.objects.get_or_create(name=room_data['name'])

validated_data.update({'room': room})
reservation = Reservation.objects.create(**validated_data)

然后将房间添加到预订实例:

room = models.ForeignKey(
    'Room', 
    null=True, blank=True,
    verbose_name='Номер', 
    on_delete=models.CASCADE,
)