Tuesday, May 3, 2016

Querying a model with a ForeignKey

I have two tables in a sqlite3 DB, PostModel and TopicModel. The PostModel has fields id, post, author, pub_date and topicid. This last fields topicid has a foreignkey to the other table Postmodel. PostModel has the fields id, topic.
There is a one-to-many relation from the TopicModel to the PostModel. So a Topic can have many posts but a post can only have one topic.
I would like to create query the PostModel to get the latest post for each topicid.
So something like, SELECT PostModel.topicid WHERE date_pub is the latest. But i would like to use the Django Query API not SQL.
My models look like this,

class TopicModel(models.Model):
    topic = models.CharField(max_length=300)
    extra = models.CharField(max_length=100)

    def __str__(self):              # __unicode__ on Python 2
            return self.topic

class PostModel(models.Model):
    post = HTMLField(blank=True)
    pub_date = models.DateTimeField('date published')
    author = models.CharField(max_length=30)
    topicid = models.ForeignKey(TopicModel, related_name = 'topicThing')

    def __str__(self):              # __unicode__ on Python 2
            return self.post

Here is the view

def thread(request, id):
    if request.method == "POST":
        print 'we are inside POST'
        pk = id
        tform = get_object_or_404(TopicModel, pk=id)
        Pform = PostForm(request.POST)
        if Pform.is_valid():
            # tform = Tform.save(commit=False)
            pform = Pform.save(commit=False)
            pform.topicid = tform
            # pform.topicid = pk
            pform.author = request.user
            pform.pub_date = timezone.now()
            pform.save()
            # return redirect('post_detail', pk=post.pk)
            return redirect('thread', id)
    else:
        pk=id
        pModel = reversed(PostModel.objects.all().filter(topicid_id=pk))
        postform = PostForm()
    return render(request, 'thread.html', {'pModel': pModel, 'postform' : postform})

Thanks

--
You received this message because you are subscribed to the Google Groups "Django users" group.
To unsubscribe from this group and stop receiving emails from it, send an email to django-users+unsubscribe@googlegroups.com.
To post to this group, send email to django-users@googlegroups.com.
Visit this group at https://groups.google.com/group/django-users.
To view this discussion on the web visit https://groups.google.com/d/msgid/django-users/8dc3a17e-850e-4b5f-91d3-1909c45f97a8%40googlegroups.com.
For more options, visit https://groups.google.com/d/optout.

No comments:

Post a Comment