tortoise / tortoise-orm

Familiar asyncio ORM for python, built with relations in mind
https://tortoise.github.io
Apache License 2.0
4.39k stars 359 forks source link

OnetoOneField Relationship returns a queryset instead of an instance of related class #1474

Open Klvxn opened 10 months ago

Klvxn commented 10 months ago

Parent field of child class (in a One-to-One relationship) returns a queryset instead of an instance of the parent class.

To Reproduce

class Room(models.Model):
    id = fields.IntField(pk=True)
    room_number = fields.IntField(index=True, unique=True)

    reservation: fields.ReverseRelation["Reservation"]
    # Other fields

    def __str__(self):
        return f"Room: {self.room_number}"

class Reservation(models.Model):
    id = fields.IntField(pk=True)
    room = fields.OnetoOneField("models.Room", related_name="reservation", on_delete=fields.CASCADE)
    # Other fields

    def __str__(self):
        return f"Reservation for room: {self.room.room_number}"

room = await Room.create(id=1, room_number=001)
reservation = await Reservation.create(id=1, room=room)
print(reservation)   # output: Reservation for room: <tortoise.queryset.QuerySet object at 0x000001975CEF3EF0>

Expected behavior The print statement should display the room number instead of the queryset object print(reservation) # output: Reservation for room: 001

Additional context Changing the str() method of the Reservation class to

# Skipped previous code

    def __str__(self):
        room = self.room.first()
        return f"Reservation for room: {room.room_number}"

and printing an instance of the Reservation class still gives the queryset object instead of the room_number