views:

15

answers:

1

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

+1  A: 

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)
TokenMacGuy
Thanks TokenMacGuy, So all the Post needs is to be referred to in ForiegnKey? Like, I don't have to explicitly define the relationship from with Post?
JonoRR
That's right. there'd be no way of referring to a collection of elements without that reference itself being a collection. The relational model has a different way of handling that, and this is reflected in the django ORM.
TokenMacGuy
Hmm. Is the Django Admin supposed to be able to deal with that? 'Cause right now it looks like it added a single URLField form. =/
JonoRR
Hey again TokenMacGuy, I really appreciate the help. Got it all working, though I note that the admin always has +3 URLFields than I have filled in. Not an issue though.
JonoRR
Oh, for the sake of anyone who comes accross the same problem, you have to iterate over myPost.url_set.all() rather than myPost.url_set.
JonoRR
heh, that'll teach me to post code without testing it. fixed.
TokenMacGuy
The number of blank fields is configurable with the `InlineModelAdmin.extra` (http://docs.djangoproject.com/en/dev/ref/contrib/admin/#django.contrib.admin.InlineModelAdmin.extra) parameter. set this to zero to have no extra fields.
TokenMacGuy