0

I'm trying to keep my project well organized, so I try to keep it splitted to apps. Assume a blog app with a BlogPost model. Now I add to that a Tag app, which has a Tag model with foreign key to Post. Now if I want to write a method get_tags(), in the Blog class, that would be circular reference. So is that a bad design? Maybe I should not write such method on the blog, or such related models should simply be in the same app?
I'm Simply trying to learn how to organize my (big) project. I've read a lot about django app concept, stil haven't found a right way

user3599803
  • 6,435
  • 17
  • 69
  • 130

1 Answers1

1

The point here is that Django automatically creates reverse lookup when you create a ForeignKey or ManytoManyField. Assuming your models are as follows:

BlogPost Model

from django.db import models

class BlogPost(models.Model):
    title = models.CharField(_('title'), max_length=200)
    slug = models.SlugField(_('slug'), unique_for_date='publish')
    author = models.ForeignKey(User, blank=True, null=True)
    body = models.TextField(_('body'), )
    publish = models.DateTimeField(_('publish'), default=datetime.datetime.now)
    created = models.DateTimeField(_('created'), auto_now_add=True)

Tag Model

from django.db import models    
from Blog.models import BlogPost

class Tag(models.Model):
    Post = models.ForeignKey(BlogPost,related_name="tags")

Now, assuming you are generating the Tags of a post in a view, you can basically get all the tags of a post by just calling blogpost.tags_set where blogpost is a model instance of BlogPost.

kreddyio
  • 144
  • 5
  • 15
  • Ans what if I want only specific tags let's say from a specific date, or the latest? Should I write that in a method. The point is about design - if it is correct to split such models into apps. I commonly see they should after some reading – user3599803 May 25 '16 at 06:58
  • @user3599803 that would just be `blogpost.tags_set.filter(created=date)` or something of that sort – kreddyio May 25 '16 at 08:30
  • @user3599803 And yeah it's perfectly fine to split your models into different apps. It would actually help in the long run to account for things as they are modularized in different apps and easy to pinpoint. – kreddyio May 25 '16 at 12:33