Django模型实例引用不保存外键

时间:2015-07-09 16:18:00

标签: django django-rest-framework

我有2个型号:

class Business(models.Model):
     ... #some fields

class Order(models.Model):
    business = models.ForeignKey(Business)

在我的一个观点中,我正在努力按照以下方式保存业务:

def view_name(request):
    business_id = request.DATA['business'] #using Django Rest
    business = Business.objects.get(id=business_id)
    order = Order(business=business)
    order.save()
    return Response('some response')

视图不会抛出任何错误,但是当我在Django Admin或DB Admin视图中打开订单时,它显示没有链接的业务。这是为什么?我哪里出错了

编辑:好的,我已经删除并重新创建了数据库,现在我可以在PostGresAdmin中看到business_id,但我没有在我的Django管理面板中看到它。附上截图:

截图

我的管理员:

Admin Panel not showing associated business

我的PG管理工具:

PGAdmin showing business

3 个答案:

答案 0 :(得分:0)

试试这个:

def view_name(request):
    business_id = request.DATA['business'] #using Django Rest
    business = Business.objects.get(id=business_id)
    order = Order.objects.create(business=business)
    order.save()
    return Response('some response')

答案 1 :(得分:0)

简单地说:

business = Business.objects.get(id=business_id)
order = business.order_set.create()

答案 2 :(得分:0)

检查返回的数据,可能无法获得预期的数据。

def view_name(request):
    business_id = request.DATA.get('business', None) #using Django Rest
    if business_id:
        business = Business.objects.get(id=business_id)
        except Business.Multiple
        order = Order(business=business)
        order.save()
        return Response('some response')
     return Response("Could not create Order")