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