开发者

Database Design: ordered many-to-many relationship

开发者 https://www.devze.com 2023-01-16 05:39 出处:网络
In Django, I have the following models: class Pink(models.Model): ... class White(models.Model): ... pinks = mod开发者_JAVA百科els.ManyToManyField(Pink)

In Django, I have the following models:

class Pink(models.Model):
    ...

class White(models.Model):
    ...
    pinks = mod开发者_JAVA百科els.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...)


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.

0

精彩评论

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