Django模型定义种族 [英] Django Model Definition Race

查看:90
本文介绍了Django模型定义种族的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何处理您有一个依赖于模型(B)被定义的模型(A)的情况,但是模型(B)也依赖于定义的模型(A)。



例如,我有

 类事件(models.Model):
competition_start = models.DateField()
competitors = models.ManyToManyField(picture)
results = models.CommaSeparatedIntegerField(max_length = 20)

类图片(models.Model):
uploader = models.OneToOneField(UserProfile)
upload_date = models.DateField()
image = models.ImageField(upload_to =media)
score = models.DecimalField(max_digits = 10 ,decimal_places = 10)
score_RD = models.DecimalField(max_digits = 10,decimal_places = 10)
rated = models.BooleanField()
last_competed = models.DateField()
竞争= models.OneToOneField(event)

竞争对手领域依赖于定义的图片,但图片依赖于ev被定义。请注意,每张图片(A)与事件共享一对一关系,但事件可能涉及多个其他图片(set(S)-A)。



我尝试交换到

  competitors = models.ManyToManyField (图)
user_pic = models.OneToOneField(图片)

内部的事件和摆脱的领域'竞争',但我相信SQL不允许这个。有人可以解释为什么吗?



如果我需要一个字段的OneToOne关系和
与另一个字段的ManyToMany关系,我应该执行什么修复? (在两个相同的类之间)



谢谢:)

解决方案

您可以将类名的字符串传递给 OneToOne ForeignKey 的定义,并将其评估为懒惰

  competitors = models.ManyToManyField('picture')

此外,模型类名称的惯例是camel-case(例如'picture'=>'Picture','event'=>'Event')。 p>

How do you deal with the case where you have a model (A) that relies on model (B) being defined, but model (B) also relies on model(A) being defined.

For instance, I have

class event(models.Model):
    competition_start = models.DateField() 
    competitors = models.ManyToManyField(picture)
    results = models.CommaSeparatedIntegerField(max_length=20)

class picture(models.Model):
    uploader = models.OneToOneField(UserProfile)
    upload_date = models.DateField()
    image = models.ImageField(upload_to="media")
    score = models.DecimalField(max_digits=10,decimal_places=10)
    score_RD = models.DecimalField(max_digits=10,decimal_places=10)
    rated = models.BooleanField()
    last_competed = models.DateField() 
    competition = models.OneToOneField(event) 

The competitors field relies on picture being defined but picture relies on event being defined.

Note that each picture (A) shares a one to one relationship with an event, but the event can involve multiple other pictures (set(S)-A).

I tried swapping over to putting

competitors = models.ManyToManyField(picture) 
user_pic = models.OneToOneField(picture)

inside of event and getting rid of the field 'competition', but I believe SQL does not allow this. Can someone explain why?

What fix should I perform if I need a OneToOne relationship for one field and a ManyToMany relationship with another? (between the two same classes)

Thank you :)

解决方案

You can pass in the string of the class name to the definition of OneToOne and ForeignKey and have it evaluated "lazily".

competitors = models.ManyToManyField('picture')

Also, the convention for model class names is camel-case (e.g. 'picture' => 'Picture', 'event' => 'Event').

这篇关于Django模型定义种族的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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