Skip to content

ManyToMany relation with extra field #612

Open
@kampfire-crafter

Description

@kampfire-crafter

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 ?

Metadata

Metadata

Assignees

No one assigned

    Labels

    enhancementNew feature or request

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions