pythondjangodjango-modelsdjango-rest-frameworkjsonresponse

Django save() is not properly saving my object


I have two models one named Post and the other Journey. Each Journey contains a query set of Post objects. When I add a post to the posts of Journey and save both the new Post and the Jounrey, the post does save properly but the Journey doesn't. The Post is beign properly created because in my JourneyView it is displayed after it is created but when I refresh the Post no longer appears as part of the Journey. I checked the database manually and the new post is saved and the object does exist it is just not being saved as part of the Journey.

This is the function I am using to create the post:

#Create post
@api_view(['POST'])
def post_create(request):
    form = PostForm(request.POST)
    attachment = None
    attachment_form = AttachmentForm(request.POST, request.FILES)
    #journeys = Journey.objects.filter(created_by_id=request.user.id)
    #journey = Journey.objects.get(id = post.journeyID)


    if attachment_form.is_valid():
        attachment = attachment_form.save(commit=False)
        attachment.created_by = request.user
        attachment.save()

    if form.is_valid():
        post = form.save(commit=False)
        post.created_by = request.user
        post.save()

        journey = Journey.objects.get(id = post.journeyID)
        #journey.posts.set(journey.posts.all())
        journey.save()
        #save_Journey(post.journeyID)

        if attachment:
            post.attachments.add(attachment)

        user = request.user
        user.posts_count = user.posts_count + 1
        user.save()

        serializer = PostSerializer(post)

        return JsonResponse(serializer.data, safe=False)
    else:
        return JsonResponse({'error': 'add somehting here later!...'})

I already tried using a for loop to save all of the journeys that exits:

for journey in Journey.objects.all():
    journey.save()

But again only the post object was being saved and when I refreshed the page the Journey went back to not containing the new post.


Solution

  • Instead of fetching the Journey object, updating it, and then saving it, you can directly use the posts relationship manager of the Journey to add the new post to the list of posts associated with that journey.

    journey = Journey.objects.get(id=post.journeyID)
    journey.posts.add(post)
    journey.save()
    

    journey.posts.add(post) is a concise way of associating the new post with the journey