Bernardo Olisan
Bernardo Olisan

Reputation: 675

Django models: how to get an model object in my views

So I have this models

class ThreadManager(models.Manager):
    def by_user(self, user):
        qlookup = Q(first=user) | Q(second=user)
        qlookup2 = Q(first=user) & Q(second=user)
        qs = self.get_queryset().filter(qlookup).exclude(qlookup2).distinct()
        return qs

    def get_or_new(self, user, other_username): # get_or_create
        username = user.username
        if username == other_username:
            return None
        qlookup1 = Q(first__username=username) & Q(second__username=other_username)
        qlookup2 = Q(first__username=other_username) & Q(second__username=username)
        qs = self.get_queryset().filter(qlookup1 | qlookup2).distinct()
        if qs.count() == 1:
            return qs.first(), False
        elif qs.count() > 1:
            return qs.order_by('timestamp').first(), False
        else:
            Klass = user.__class__
            user2 = Klass.objects.get(username=other_username)
            if user != user2:
                obj = self.model(
                        first=user, 
                        second=user2
                    )
                obj.save()
                return obj, True
            return None, False


class Thread(models.Model):
    first        = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, related_name='chat_thread_first')
    second       = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, related_name='chat_thread_second')
    updated      = models.DateTimeField(auto_now=True)
    timestamp    = models.DateTimeField(auto_now_add=True)
    thread_notification = models.IntegerField(default=0)
    
    objects      = ThreadManager()

in my model Thread I want to get the object thread_notifications, so I make my views like this

def new_notification_thread(request):
    thread_notifier = Thread.objects.filter(pk=1)
    thread_notifier.thread_notification += 1
    thread_notifier.save()

    return JsonResponse(serializers.serialize('json', [thread_notifier]), safe=False)

The problem is that when I run my code I get

Thread matching query does not exist.

does anybody know what is going on?

Upvotes: 0

Views: 298

Answers (1)

ino
ino

Reputation: 1125

thread_notifier = Thread.objects.filter(pk=1)

You are having this error becuse the item associated with id = 1 does not exist/deleted.So when you try to access a non existing item you are being shown error.Try accessing a existing id and you should be good to go.

okay, dont use filter method to avoid F() expression.instead do this:

thread_notifier = Thread.objects.get(pk=1)

It wont give you queryset so you can directly access all attributes. now just following:

thread_notifier.thread_notification += 1
thread_notifier.save()

But you have to use filter method when there are more than 1 items.

Upvotes: 4

Related Questions