Home > Net >  Django validate the input as a valid foreign key
Django validate the input as a valid foreign key

Time:07-18

In django rest framework, have a POST api that creates a City object. However it also receives a list of ids of stadiums.

What is the best way to validate each of the ids are valid stadium_ids (present and not deleted in the table Stadiums).

CodePudding user response:

First put list of ids in a set to distinct probable repeated ids:

ids = set(ids)

Then filter stadiums based on this ids:

stadiums = Stadium.object.filter(id__in=ids)

If some stadiums are not present in database, then count of stadiums is less than size of ids:

if len(ids) != len(stadiums):
    # Handle Error
  • Related