开发者

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


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.


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)


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

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜