Fetching few fields from a Reverse Relation #451
Answered
by
collerek
igormorgado
asked this question in
Q&A
-
I would like to retrieve specified fields in a reverse foreign key relation. But when I use await Model.objects.select_related('fkey__column').get(pk=num) I could get Below a snippet to show my issue from typing import Optional, List
import ormar as orm
import databases
import sqlalchemy
DATABASE_URL = 'sqlite:///db.sqlite'
database = databases.Database(DATABASE_URL)
metadata = sqlalchemy.MetaData()
class BaseMeta(orm.ModelMeta):
metadata = metadata
database = database
class Person(orm.Model):
id: int = orm.Integer(primary_key=True)
name: str = orm.String(max_length=32)
class Meta(BaseMeta):
tablename = "persons"
class Item(orm.Model):
id: int = orm.Integer(primary_key=True)
name: str = orm.String(max_length=32)
person: Optional[Person] = orm.ForeignKey(Person, nullable=True)
on_sale: bool = orm.Boolean(nullable=False, default=False)
class Meta(BaseMeta):
tablename = "items"
async def create_db():
engine = sqlalchemy.create_engine(DATABASE_URL)
await database.connect()
metadata.drop_all(engine)
metadata.create_all(engine)
return metadata
async def tests():
person = await Person.objects.create(name='Person')
itema = await Item.objects.create(
name='ItemA',
person=person,
on_sale=False
)
itemb = await Item.objects.create(
name='Itemb',
person=person,
on_sale=False)
person_db1 = await Person.objects.select_related('items').get(pk=1)
assert person_db1.items[0].name == 'ItemA'
# This fails with alias name issues
person_db2 = await Person.objects.select_related('items__name').get(pk=1)
assert person_db2.items[0].name == 'ItemA'
async def disconnect_db():
await database.disconnect()
async def main():
await create_db()
await tests()
await disconnect_db()
if __name__ == "__main__":
import asyncio
asyncio.run(main()) |
Beta Was this translation helpful? Give feedback.
Answered by
collerek
Nov 23, 2021
Replies: 1 comment 5 replies
-
With |
Beta Was this translation helpful? Give feedback.
5 replies
Answer selected by
igormorgado
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
With
select_related
you can only select nested models, not the columns. To select subset of fields, combineselect_related
withfields
and/orexclude_fields
.