如何设置这个? [英] How do I set this up?

查看:141
本文介绍了如何设置这个?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我要设置我的模型,以便我的数据具有此关联:

I'm trying to set up my models so my data has this association:

这里是我认为代码应该是这样:

Here is what I'm thinking the code should look like:

# green model
class green(models.Model):

# grey model
class grey(models.Model):

# blue model
class blue(models.Model):
    green = models.ManyToManyField(green, blank=True, null=True)
    grey = models.ForeignKey(grey, blank=True, null=True)

# red model
class red(models.Model):
    red = models.ManyToManyField(blue, blank=True, null=True)

这是一个红色可以有许多蓝色,绿色和灰色。

That is a red can have many blues, which can have many greens and a grey.

我设置好了吗?我能够按照路径获得这些数据吗?

Am I setting this up right? Will I be able to follow a path to get to this data?

例如:查找所有绿色对象和blue1的灰色对象

For example: find all the green objects and the grey object of blue1

在我的模型中将它们关联?

When I say ids, do I need all the blues to have a red id?

推荐答案

您的图表显示了一切之间的严格关系,即。

Your diagram shows a strict relationship between everything, ie. a green belongs to only one blue and a gray thing belongs to only one blue.

如果这是真的,那么你的建模将不起作用,你需要 OneToOneFields 来映射灰度。此外,在您的 ForeignKey 中添加 related_name 允许您在查询时使用更干净的名称。例如, blue_object.greens 与。 blue_object.green_set

If this is true, then your modeling won't work, you need OneToOneFields to map the grays. Also, adding a related_name to your ForeignKeys allows you to have a "cleaner" name when querying. For example, blue_object.greens versus. blue_object.green_set

以下代码允许红色对象拥有一个具有自己的绿色对象和单个对象的显式(非共享)集合 blue 灰色对象。

The following code allows a red object to have an explicit (non-shared) set of blue objects with their own set of green objects and a single gray object which they don't share.

# green model
class green(models.Model):
    blue = models.ForeignKey(blue, blank=True, null=True, related_name="greens") # I belong to one blue

# grey model
class grey(models.Model):
    gray = models.OneToOneField(grey, blank=True, null=True)
    # Put here for consistancy with pointing to a parent.

# blue model
class blue(models.Model):
    red = models.ForeignKey(red, blank=True, null=True, related_name="blues") )

# red model
class red(models.Model):
    pass

这篇关于如何设置这个?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆