Django to_field不起作用 [英] Django to_field not working

查看:119
本文介绍了Django to_field不起作用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有两个表 RoomPriceDetails HotelDetails . RoomPriceDetails 有一个外键,我想指向名为 HotelDetails hotel_id 的主键字段.我为此使用了 to_field 属性,但似乎我在某些地方出错了.它向我显示

I have two tables RoomPriceDetails and HotelDetails. RoomPriceDetails has a foreign key which I want to point to the primary key field named hotel_id of HotelDetails. I used to_field attribute for this, but it seems I am going wrong some where. It shows me error like

ValueError:以10为基数的int()无效文字:'BMH-1'.

当我尝试在 RoomPriceDetails 中添加 hotel_id 'BMH-1'时."BMH-1"是 HotelDetails 中的酒店ID.如果我错了,什么是使我的外键指向 HotelDetails 中的 hotel_id 字段以接受这些值的最佳方法.

when I try to add the hotel_id 'BMH-1' in RoomPriceDetails. 'BMH-1'is a hotel id in HotelDetails. If I am wrong what is the best way to make my foreign key to point to my hotel_id field in HotelDetails to accept those values.

我的模特:

class RoomPriceDetails(models.Model):
    room_type = models.CharField(max_length=255, primary_key=True)
    hotel = models.ForeignKey(HotelDetails, to_field='hotel_id')
    price_per_day = models.PositiveIntegerField(default=0)

class HotelDetails(models.Model):
    hotel_id = models.AutoField(primary_key=True, db_column='hotel_id')
    name = models.CharField(max_length=255)
    email = models.CharField(max_length=255)
    reg_no = models.CharField(max_length=255)
    contact_no = models.CharField(max_length=10)
    owner_name = models.CharField(max_length=255)
    owner_email = models.CharField(max_length=255)
    owner_contact_no = models.CharField(max_length=255)
    address = models.CharField(max_length=400)
    city = models.CharField(max_length=255)
    state = models.CharField(max_length=255)
    pincode = models.CharField(max_length=6)

推荐答案

Autofield can only hold an integer, by default Django sets auto field.

一个IntegerField,它根据可用的ID自动递增.您通常不需要直接使用它;如果没有另外指定,主键字段将自动添加到模型中.

An IntegerField that automatically increments according to available IDs. You usually won’t need to use this directly; a primary key field will automatically be added to your model if you don’t specify otherwise.

您要添加的是 primary_key 转到您的CharField

What you would like is add primary_key to your CharField

Field.primary_key 如果为True,则此字段是模型的主键.

Field.primary_key If True, this field is the primary key for the model.

在您的示例中:

class HotelDetails(models.Model):
    hotel_id = models.CharField(primary_key=True, db_column='hotel_id', max_length=10)

主键不是整数会降低数据库性能

Having primary key not being integer can decrease your DB performance

这篇关于Django to_field不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆