Reputation: 9610
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
Upvotes: 2
Views: 353
Reputation: 17713
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.
Upvotes: 4
Reputation: 125157
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")
Upvotes: 5