开发者

Django model defining list of URLFields

I'm pretty new to relational database开发者_Go百科s 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).


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)
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜