tortoise / tortoise/tortoise-orm

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

Open
#1,474 0 comments 0 reactions 0 assignees View on GitHub

Nobody has claimed this yet.

Dominant language
Python
Stars
5.6k
Forks
516
Avg merge
2d 21h
Merged PRs (30d)
9

Description

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

Contributor guide

Open the contributing guide

First steps

  1. Read the whole issue, then the project's contributing guide.
  2. Comment on the issue to say you are picking it up — it saves two people doing the same work.
  3. Fork the repository and make your change on a branch.
  4. Open a pull request that references the issue number.

Research direction

Start by reproducing the issue with the provided Room and Reservation models and the shown print statement. Trace how the OneToOneField relation is accessed and compare it with the expected related instance behavior; done means printing a Reservation shows the room number rather than a QuerySet object.

Written by the indexing model from the issue text.

Assessment

Tech stack
python
Domain
backend, databases
Issue type
Bug
Difficulty
3/5
Estimated time
1-2 days
Activity status
Stale
Clarity
Mostly clear
Newbie friendliness
45/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.