Django db 2个外键之一不返回对象

2024-10-03 11:26:34 发布

您现在位置:Python中文网/ 问答频道 /正文

在MySQL中,我有3个表:Client、Room和ClientRoom,它们指向前面的两个表

-- -----------------------------------------------------
-- Table `client`
-- -----------------------------------------------------
CREATE TABLE IF NOT EXISTS `client` (
  `id` INT NOT NULL,
  `name` VARCHAR(255) NULL,
  PRIMARY KEY (`id`)
)
ENGINE = InnoDB
DEFAULT CHARACTER SET = utf8
COLLATE = utf8_general_ci;


-- -----------------------------------------------------
-- Table `room`
-- -----------------------------------------------------
CREATE TABLE IF NOT EXISTS `room` (
  `id` INT NOT NULL,
  `price` DECIMAL(18,2) NOT NULL,
  `apart_num` INT NOT NULL,
  `free` BOOL default TRUE,
   PRIMARY KEY (`id`)
  )
ENGINE = InnoDB
DEFAULT CHARACTER SET = utf8
COLLATE = utf8_general_ci;


-- -----------------------------------------------------
-- Table `client-room`
-- -----------------------------------------------------
CREATE TABLE IF NOT EXISTS `client_room` (
  `id` INT PRIMARY KEY AUTO_INCREMENT,
  `client_id` INT NOT NULL,
  `room_id` INT NOT NULL,       
  `date_in` DATETIME NOT NULL,
  `date_out` DATETIME NOT NULL,
INDEX `fk_client_room_idx` (`client_id` ASC),
CONSTRAINT `fk_client_room_id`
    FOREIGN KEY (`client_id`)
    REFERENCES `client` (`id`)
    ON DELETE NO ACTION
    ON UPDATE NO ACTION,
INDEX `fk_room_idx` (`room_id` ASC),
CONSTRAINT `fk_room_id`
    FOREIGN KEY (`room_id`)
    REFERENCES `room` (`id`)
    ON DELETE NO ACTION
    ON UPDATE NO ACTION
  )
ENGINE = InnoDB
DEFAULT CHARACTER SET = utf8
COLLATE = utf8_general_ci;

使用python manage.py inspectdb我得到了

class Client(models.Model):
    id = models.IntegerField(primary_key=True)
    name = models.CharField(max_length=255, blank=True, null=True)

    class Meta:
        managed = False
        db_table = 'client'


class ClientRoom(models.Model):
    client = models.ForeignKey(Client, models.DO_NOTHING)
    room = models.ForeignKey('Room', models.DO_NOTHING)
    date_in = models.DateTimeField()
    date_out = models.DateTimeField()

    class Meta:
        managed = False
        db_table = 'client_room'

class Room(models.Model):
    id = models.IntegerField(primary_key=True)
    price = models.DecimalField(max_digits=18, decimal_places=2)
    apart_num = models.IntegerField()
    free = models.IntegerField(blank=True, null=True)

    class Meta:
        managed = False
        db_table = 'room'

问题是,要创建ClientRoom对象,我需要客户机id和房间对象id,而不是两个对象:一个是客户机,另一个是房间

def clientRoom(request):#This works
    if request.method == "POST":
        clientRoom = ClientRoom()
        clientRoom.client_id = request.POST.get("client_id")
        room=Room()
        room.id = request.POST.get("room")
        clientRoom.room = room
...
return render(request, "clientRoom.html", {"clientRoom": clientRoom})

def clientRoom(request):#This isn't working
    if request.method == "POST":
        clientRoom = ClientRoom()
        client=Client()
        client.id=request.POST.get("client_id")
        clientRoom.client_id = client
        room=Room()
        room.id = request.POST.get("room")
        clientRoom.room = room
...
return render(request, "clientRoom.html", {"clientRoom": clientRoom})

这对我来说毫无意义,这也阻碍了进一步的进步。 我一直在制作gui站点(在HTML上),它显示房间号,应该显示客户机名称,而不是id。但我无法获取客户机名称,因为与房间相比,ClientRoom不完全包含客户机对象

<table><!-- Here I got only Client id, cannot access name by client_id.name,because client_id is just a number, while room is an object of Room, and i can access it's id -->
        {% for record in clientsRooms %}
        <tr> 
            <td>{{ record.client_id }}</td> <td>{{ record.room.id }}</td>
            <td>{{ record.date_in }}</td> <td>{{ record.date_out }}</td> 
            
        </tr>
        {% endfor %}
    </table>

我应该做些什么更改以使ClientRoom构造函数需要2个对象(客户机和房间,而不仅仅是房间对象和客户机id)


Tags: clientiddate客户机modelsrequestnotutf8
1条回答
网友
1楼 · 发布于 2024-10-03 11:26:34

将对象指定给外键字段时,不要将其指定给以_id结尾的字段。这就是你的一个例子不起作用的原因。您正在执行clientRoom.client_id = client,但客户机是Client对象,而不是ID

以下所有分配方法均适用于您的模型:

client_room = ClientRoom()
client_room.client_id = some_client_id
client_room.room_id = some_room_id


client_room = ClientRoom()
client_room.client = some_client_object
client_room.room = some_room_object


client_room = ClientRoom(client=some_client_object, room=some_room_object)


client_room = ClientRoom(client_id=some_client_id, room_id=some_room_id)


# And you can assign one by ID and the other by object, as you've already discovered.

相关问题 更多 >