python Django 一对多模型
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/2039958/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Django One-To-Many Models
提问by Dan
The following models describe a vulnerability and the URLs out on the internet that reference that vulnerability. Assume that each URL only ever talks about 1 vulnerability, and that many URLs will discuss that vulnerability. Is this the correct way to lay out the model?
以下模型描述了一个漏洞以及 Internet 上引用该漏洞的 URL。假设每个 URL 只讨论 1 个漏洞,并且许多 URL 将讨论该漏洞。这是布置模型的正确方法吗?
class Vuln(models.Model):
pub_date = models.DateTimeField("Publication Date")
short_description = models.CharField("Description", max_length=70)
reference_urls = models.ForeignKey(Url, unique=True, blank=True, verbose_name="Reference URLs")
vendor = models.ForeignKey(Vendor, verbose_name="Vendor")
class Url(models.Model):
url = models.URLField("URL", max_length=200)
The Admin application gives a 'select' box for the reference URLs, which isn't what I want. When I add a new vulnerability object, all of the existing URLs that have been entered show up in that dropdown, which is again unnatural. I feel like this should behave very similar to how a blog comment would, ie. the comment applies to a single blog entry and none other and that one blog entry may have many comments. How do I express this in a Django model?
Admin 应用程序为参考 URL 提供了一个“选择”框,这不是我想要的。当我添加一个新的漏洞对象时,所有已输入的现有 URL 都显示在该下拉列表中,这又是不自然的。我觉得这应该与博客评论的行为非常相似,即。评论适用于单个博客条目,而不适用于其他博客条目,并且一个博客条目可能有许多评论。我如何在 Django 模型中表达这一点?
回答by Alex
It should be more like this:
它应该更像这样:
class Vuln(models.Model):
pub_date = models.DateTimeField("Publication Date")
short_description = models.CharField("Description", max_length=70)
vendor = models.ForeignKey(Vendor, verbose_name="Vendor")
class Url(models.Model):
url = models.URLField("URL", max_length=200)
vulnerability = models.ForeignKey(Vuln)
If you're saying each Url talks about a specific vulnerability, then there is your relation in the Django DBM :)
如果你说每个 Url 都在谈论一个特定的漏洞,那么在 Django DBM 中有你的关系:)
As for the vendor field, you simply add another class, much like Class Vuln. For example:
至于供应商字段,您只需添加另一个类,就像 Class Vuln 一样。例如:
class Vendor(models.Model):
field_names_go_here = models.TextField(max_length=70)
short_description = models.CharField("Description", max_length=70)
Hope this helps! Regards, Alex
希望这可以帮助!问候,亚历克斯