Django: creating model with undefined number of fields

I am trying to create a model for an Article site. I want to link each article to 3-5 linked articles, so I am thinking of generating 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 is possible to make a foreign key relationship to the same model. Also if, for example, I decide to link 6, 7 articles together, how would this work, I need to write linked 4, 5, 6 .... in the model? I want to have a more general solution, so if I link more articles I don't have to redefine the code over and over again

What I am thinking about is not to distribute article models with bound fields. (It looks ugly) Maybe we should create another model? For example: ArticleSet

But how to define there an unlimited list (no limitation of subjects) .. Could you suggest a way?

Thank you in advance

+2


source to share


2 answers


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

      

+5


source


Basically a ManyToMany can be thought of as an array. So in your 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 %}

      



More generally, the Django docs (and the free online Django Book ) are about as good as the FOSSland ones. I highly recommend getting a good cup of coffee and doing some serious reading. There are also tons of good things 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 idea of ​​what you can do with it.

+4


source







All Articles