Search code examples
pythondjangodjango-modelsdjango-users

is it possible to Only pull related users through foreign key relationship, once in django


Hi im fairly new to the amazing world of django!

Basically im working on a project that requires me to create a fairly unique email notifications system that users can use to refine the updates they recieve via email when new blog posts are made on the site.

I think im gonna have a ton of questions about this project as its proving to be a really steep learning curve so i thought id try it all myself first then run here for help when i get stuck!

Basically users can opt in to recieve updates for the following ALl new blog posts Or select from a check box form thier favourite authors etc

The first thing i have run into is pulling the users out from the database. I know how to get all the user details for each blog but this obviously gives me back duplicate user details for users that have published more than one blog. so i need a way to only get the user info for those users who have posted a blog and only get thier details once.

MODEL

class Blog(models.Model):

     user = models.ForeignKey(User, help_text = "The User posting this blog entry")
     news = models.ForeignKey(News, unique = True, blank = True, null = True, help_text = "Is this Blog entry related to a news posts IE and Expert Analysis")
     title = models.CharField(max_length = 120, help_text = "The Title of this blog entry")
     slug = models.SlugField(max_length = 150, help_text = "This Field is auto-populated by the title field, its simply used for the CMS urls")
     info = models.TextField()
     categories = models.ManyToManyField(Categories)
     sectors = models.ManyToManyField(Sectors)
     tags = models.ManyToManyField(Tags)
     published = models.DateTimeField()
     status = models.CharField(max_length=1, choices=STATUS_CHOICES, default = 'd')

     class Meta:
         verbose_name_plural = "Blog entries"
         verbose_name = "Blog"
         ordering = ['-published']

     def __unicode__ (self):
         return self.title

As you can i see i am using django's user model as a foreign key to store the authors details. Should i scrap this approach and set up a seperate model for the blog authors or can what i am trying to do be achieved using the built in User model.

So to conclude what i am aiming for is be able to get a list of all the users that have posted a blog post but only grab their details once thus giving me a list of names and ids so that i can create a form using check boxes that the user can tick to opt in to receive updates!

Thanks in advance for any help!!


Solution

  • You can do a single query for users that have at least one blog entry:

    User.objects.exclude(blog=None)