sqlite 如何在Django REST框架中创建与其他模型相关的对象[复制]

bvk5enib  于 2022-11-14  发布在  SQLite
关注(0)|答案(2)|浏览(168)

这个问题在这里已经有答案

Cannot assign must be a instance. Django(3个答案)
上个月关门了。
我有3种模式:用户,理发师和预订。在我的createBooking视图中,我弄不清楚如何传递用户和理发师的ID。以下是我的代码:
这一观点:

def createBooking(request):
    data = request.data
  
    booking = Booking.objects.create(
        barber_id = data['barberb_id'],
        customer_id = data[ 'customer_id'],
        timeslot = data['timeslot'],
        )
    serializer = BookingSerializer(booking, many=False)
    return Response(serializer.data)

预订模式:

customer_id = models.ForeignKey(User, on_delete = models.CASCADE,)
    barber_id = models.ForeignKey(Barber, on_delete = models.CASCADE)
    timeslot = models.DateTimeField('appointment')

    def __str__(self):
        return f"{self.customer_id} {self.barber_id} {self.timeslot}"

使用当前代码,我得到错误Cannot assign "['customer_id']": "Booking.customer_id" must be a "User" instance.

e5njpo68

e5njpo681#

由于您已经在模型中将属性名称指定为barber_id和Customer_id,因此必须创建对象,如下所示。

booking = Booking.objects.create(
        barber_id_id = data['barberb_id'],
        customer_id_id = data[ 'customer_id'],
        timeslot = data['timeslot'],
        )

尽管我们在末尾没有给出后缀_id,但是外键是用attribute_name+_id存储的。我们也可以在Django直接使用它。

ogsagwnx

ogsagwnx2#

我们可以定义与用户相关的模型,如下所示,并尝试将用户示例传递给Customer_id。

customer_id = models.ForeignKey(AUTH_USER_MODEL, on_delete = models.CASCADE,related_name='%(class)s_customer_id')
    
Basically it should be an user instance.  
   
from django.contrib.auth.models import User
user = User.objects.get(id=data['customer_id'])
booking = Booking.objects.create(
            barber_id = data['barberb_id'],
            customer_id = user,
            timeslot = data['timeslot'],
            )

相关问题