tortoise / tortoise-orm

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

ManyToMany relation with extra field #612

Open kampfire-crafter opened 3 years ago

kampfire-crafter commented 3 years ago

Hello,

I would like to know if it’s possible to have a ManyToMany relationship with an extra filed. I have a drug model that may contains multiple molecules models. I would like to display this relation with an additional field: quantity. I need to display the quantity at the same level as the molecule's information.

This is my endpoint :

@router.get('/', response_model=List[DrugResponse])
async def drugs():
    """Returns a list of drugs. """

    return await DrugResponse.from_queryset(Drug.all())

This is my models :

class Drug(Model):
    id = fields.IntField(pk=True)
    label = fields.CharField(max_length=128, null=False)

    class Meta:
        table = "drugs"

class DrugMolecule(Model):
    drug = fields.ForeignKeyField("models.Drug", related_name='molecules', null=False)
    molecule = fields.ForeignKeyField("models.Molecule", related_name=False, null=False)
    quantity = fields.FloatField(null=True)

    class Meta:
        table = 'drug_molecule'

class Molecule(Model):
    id = fields.IntField(pk=True)
    name = fields.CharField(max_length=128, null=False)

    class Meta:
        table = 'molecules'

    class PydanticMeta:
        exclude = ["administration_context"]

I would like that my endpoint return an object structured like this :

[
  {
    "id": 1,
    "label": "ADVIL 200mg, comprimé enrobé",
    "molecules": [
      {
        "id": 1, // molecule_id
        "name": "Ibuprofen",
        "quantity": 100 // extra field quantity
      },
      {
        "id": 2, // molecule_id
        "name": "Hydroxychloroquine",
        "quantity": 100 // extra field quantity
      }
    ]
  }
]

But for now, my endpoint return an object like this :

[
  {
    "id": 1,
    "label": "ADVIL 200mg, comprimé enrobé",
    "molecules": [
      {
        "id": 1,
        "molecule": {
          "id": 1,
          "name": "Ibuprofen"
        },
        "quantity": 100 // extra field quantity
      },
      {
        "id": 2,
        "molecule": {
          "id": 2,
          "name": "Hydroxychloroquine"
        },
        "quantity": 100 // extra field quantity
      }
    ]
  }
] 

Could you please explain me how I can get the well structured return please ?

HaoXiangQI commented 3 years ago

you can try use pydantic to generaite what you want.

FIRDOUS-BHAT commented 3 years ago

I'm havinf the same issue,

@AlexTheByte Can you please let me know that how are you submit the manytomany relationship data to the database