提问者:小点点

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


在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对象,我需要Client和Room对象的id,而不是两个对象:一个Client和一个Room。

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不完全由客户对象组成,与Room相比。

<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)?


共1个答案

匿名用户

将对象赋给外键字段时,不要将其赋给以_id结尾的字段。这就是为什么你的一个例子不起作用的原因。您正在执行clientroom.client_id=client,但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.