views:

48

answers:

1

In Django, I have the following models:

class Pink(models.Model):
    ...

class White(models.Model):
    ...
    pinks = models.ManyToManyField(Pink)
    ...



At some point, I needed to define an ordering of Pinks inside a White (in order to have White1.pinks: P1, P2, P3 instead of a random White1.pinks: P2, P3, P1), so I've created

class PinkInWhite(models.Model):
    pink = models.ForeignKey(Pink)
    white = models.ForeignKey(White)
    position = models.PositiveIntegerField("pink's position inside this white")

    class Meta:
        ordering = ['white','position']



Question 1: is this the better solution?

Question 2: This is obviously redundant: I still have a pinks field in my White model, because I need it in other situations which didn't require an ordering. Can I keep it, or is it better to remove it, and always use the PinkInWhite relation model instead?




(Model names are fictional. For simplify the question I didn't use model's real names, and talking about Mr. X and Mr. Y wouldn't help readability...)

A: 

It depends on how well-defined your intended use is.

If you're just looking for a set of ordered pinks in whites, you can just stuff everything in one table and avoid the junction table PinkInWhite.

But if you might in the future want to have other tints besides tints of red, then having pinks tied directly to white as you do is too restrictive. Just leave whites as whites, and create a junction table linking the pinks to the approriate whites (with ordering). Then you have the flexibility to make tints of blues, yellows, whatever.

But the short answer to your question, what you have will be usable.

John at CashCommons
If you do go with a join table/junction table, the way it's implemented in Django is known as using a Through model - see http://docs.djangoproject.com/en/dev/topics/db/models/#extra-fields-on-many-to-many-relationships
stevejalim