Django 模型定义 URLFields 列表

发布于 2024-09-26 13:26:22 字数 129 浏览 3 评论 0原文

我对关系数据库很陌生,这可能就是我遇到这个问题的原因,但我有一个模型 - Post。

我希望它具有可变数量的 URL,但是 Django 似乎只有 OneToManyField 需要模型(而不是字段 - URLField 是)。

I'm pretty new to relational databases and this may be why I'm having this problem but I have a model - Post.

I want it to have variable number of URLs, however Django only seems to have the OneToManyField which requires a model (not a field - which URLField is).

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

木格 2024-10-03 13:26:22

在关系数据库设计中,表中的字段始终是标量值。在您的情况下,这样的字段将是“网址”。将集合应用于行的方式是将该行与另一个表的行连接起来。用 django 的话说,这意味着您需要两个模型,一个用于 Post 对象,另一个将多个 url 与该帖子链接。

class Post(models.Model):
    pass

class Url(models.Model):
    url = models.URLField()
    post = models.ForeignKey(Post)


myPost = Post.objects.all().get()
for url in myPost.url_set.all():
    doSomething(url.url)

现在你可以通过 urls 成员访问 url,

但是如果你想让 Post 的管理页面也让你添加 url,你需要使用 InlineModelAdmin

from django.db import models
from django.contrib import admin


class Post(models.Model):
    pass

class Url(models.Model):
    url = models.URLField()
    post = models.ForeignKey(Post)


class UrlAdmin(admin.TabularInline):
    model = Url

class PostAdmin(admin.ModelAdmin):
    inlines = [UrlAdmin]

admin.site.register(Post, PostAdmin)

In relational database design, the fields in a table are always scalar values. in your case, such a field would 'a url'. The way you get a collection to apply to a row, you join that row with the rows of another table. In django parlance, that would mean that you need two models, one for the Post objects, and another that links multiple urls with that post.

class Post(models.Model):
    pass

class Url(models.Model):
    url = models.URLField()
    post = models.ForeignKey(Post)


myPost = Post.objects.all().get()
for url in myPost.url_set.all():
    doSomething(url.url)

Now you can access urls through a urls member

But if you want to get the admin page for Post to also let you add urls, you need to do some tricks with InlineModelAdmin.

from django.db import models
from django.contrib import admin


class Post(models.Model):
    pass

class Url(models.Model):
    url = models.URLField()
    post = models.ForeignKey(Post)


class UrlAdmin(admin.TabularInline):
    model = Url

class PostAdmin(admin.ModelAdmin):
    inlines = [UrlAdmin]

admin.site.register(Post, PostAdmin)
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文