How to define OneToOne
relationship to the same Model
?
I have a model called Order
which can be paired with another one Order
. Now I'm trying to figure out how to handle models for this relationship.
My ideas:
class Order(models.Model):
paired_order = models.OneToOneField(self)
OR:
class Pairing(models.Model):
order1 = models.ForeignKey(Order, related_name='pairing')
order2 = models.ForeignKey(Order, related_name='pairing')
What do you think? Which is more efficient?
I want to have simple calling of paired ones. So I would do something like:
order.paired_order
OR:
order.pairing.paired
I want this relation symmetrical so for each pair of orders I call the same thing and get paired order.
Pairing model would be a good solution because I can add additional information to this relationship, but there is a problem that I would have to detect which order is it, so I couldn't call order.pairing.order1
because I don't know whether I'm not calling the same order.
EDIT:
>>> from _app import models
>>> order1 = models.Order(flight_number="xxx")
>>> order2 = models.Order(flight_number="yyy", paired_order=order1)
>>> order1.paired_order.flight_number
RETURNS None object has not ....
The problem is that when I set order1 is a paired order for order2, I want the same thing in opposite direction. So order1.paired_order = order2
do this as well order2.paired_order = order1
.