tags:

views:

92

answers:

2

Hi

I am trying to create a model for Article site. I want to link each article with 3-5 related articles, so what I am thinking of is creating code this way:

class Article (models.Model):
    # Tiny url
    url = models.CharField(max_length = 30, unique=True)
    is_published = models.BooleanField()
    author = models.CharField(max_length = 150)
    title = models.CharField(max_length = 200)
    short_description = models.TextField(max_length = 600)
    body = tinymce_models.HTMLField()
    related1 = models.ForeignKey(Article)
    related2 = models.ForeignKey(Article)
    related3 = models.ForeignKey(Article)

But not sure if it's possible to make a foreign key relation to the same model. Also if for example, I will decide to bind 6, 7 articles together, how that will work, do I have to write related4, 5, 6....in the model? I want to have more common solution, so if I binding more articles, I don't need to redefine code again and again

What I am thinking of is not to extend Article models with related fields.. (It looks ugly) Maybe it worth creating another model? For example: ArticleSet

But how to define there unrestricted list (without limit of items)..Could you suggest a way?

Thanks in advance

+5  A: 

You need to use a ManyToManyField for this relationship.

For example:

class Article (models.Model):
    # rest of fields up to and including body
    related_articles = models.ManyToManyField("self")
Ben James
Is there a way to restrict quantity for example to 5 in this case?
Oleg Tarasenko
Just tried it :) This is really cool! I wonder how can I query all articles related to the current one in a view? Also would be really good to filter the list of available related articles somehow :(
Oleg Tarasenko
Peter Rowell
Nah, that didn't work. I'll do it in a direct answer ...
Peter Rowell
+4  A: 

Basically the ManyToMany can be treated as an array. So in the template you can do something like this:

{% for rel_art in cur_art.related_articles.all %}
    <a href="{{rel_art.url}}">{{rel_art.title}}</a>
{% endfor %}

On a more general note, the Django docs (and the free online Django Book) are about as good as it gets in FOSSland. I strongly recommend getting a good cup of coffee and doing some serious reading. There is also tons of good stuff to learn from reading the Django code itself -- it's well structured and well commented. Even going through a simple app like django.contrib.flatpages will give you some real insight to what you can do with it.

Peter Rowell
Thanks for adding the '.all', Carl. I was working with a one-beer-handicap.
Peter Rowell