toonuut
toonuut

Reputation: 1

How can I represent this in a Django model?

I'm having trouble working out what the relationships should be with this:

class Airport(models.Model):
    airlines = models.ManyToManyField(Airline)

class Airline(models.Model):
    terminal = models.CharField(max_length=200)

The problem is that each Airline is associated with a different terminal depending on which Airport is requested, so terminal can't just be static text.

Anyone know what the best way to model this is?

Thanks

Upvotes: 0

Views: 156

Answers (3)

Jordan Reiter
Jordan Reiter

Reputation: 21002

Surprised that there are so many different answers, I guess people each have their own preferences. This is how I'd do it:

class Airport(models.Model):
    name = models.CharField(max_length=200)

class Airline(models.Model):
    name = models.CharField(max_length=200)
    terminals = models.ManyToManyField('Terminal', related_name='airlines')

class Terminal(models.Model):
    name = models.CharField(max_length=200)
    airport = models.ForeignKey('Airport', related_name='terminals')

This allows for and assumes the following conditions:

  • An airline can be present in one or more terminals in a given airport
  • A terminal can have more one or more airlines
  • A terminal can only exist in a single airport

Note that in this setup airports and airlines are always linked indirectly via Terminals. I think this is a feature rather than a bug, personally. Airports always have at least one terminal, even if the terminal is the entire airport.

Or

You may consider it to be slightly more correct, from a logical point of view, to create the models like so:

class Airport(models.Model):
    name = models.CharField(max_length=200)

class Airline(models.Model):
    name = models.CharField(max_length=200)

class Terminal(models.Model):
    name = models.CharField(max_length=200)
    airport = models.ForeignKey('Airport', related_name='terminals')
    airlines = models.ManyToManyField('Airline', related_name='terminals')

In practical terms the data will behave largely the same. One could make an argument, however, that thinking of a terminal having "Airlines" makes more sense conceptually than a given airline having terminals. After all, the airline does not contain the terminals, but each terminal contains these airlines.

Upvotes: 3

Mohammad Rafiee
Mohammad Rafiee

Reputation: 711

class Airport(models.Model): airlines = models.ManyToManyField(Airline) terminal = models.CharField(max_length=200)

i think it would solve your problem use just one class instead

Upvotes: 0

Daniel Roseman
Daniel Roseman

Reputation: 599610

class Airport(models.Model):
    airlines = models.ManyToManyField(Airline, through=Terminal)

class Terminal(models.Model):
    terminal = models.CharField(max_length=200)

class Airline(models.Model):
    terminal = models.ForeignKey(Terminal)
    airport = models.ForeignKey(Airport)

Upvotes: 0

Related Questions