How can I get list of all items with query received?

Viewed 141

I am making a Django project in which I have User List which contains various Items. Each Item has its attribute like name, quantity and date.

This is my model of items:

class Item(models.Model):
    STATUS = (
        ('BOUGHT', 'BOUGHT'),
        ('NOT AVAILABLE', 'NOT AVAILABLE'),
        ('PENDING', 'PENDING'),
    )
    userlist = models.ForeignKey(userList, on_delete=models.SET_NULL, blank=True, null=True)
    item_name = models.CharField(max_length=200, null=True)
    item_quantity = models.CharField(max_length=200, null=True)
    item_status = models.CharField(max_length=200, null=True, choices=STATUS)
    date = models.DateField(null=True)

    def __str__(self):
        return self.item_name

This is my views.py:

def listView(request):
    if request.user.is_authenticated:
        fd = None
        user_id = request.user.id
        userlist, created = userList.objects.get_or_create(user_id=user_id)
        items = userlist.item_set.all()
        if request.body:
            data = json.loads(request.body)
            fd=data['date']
    else:
        items = None

    context = {'items': items}
    return render(request, 'list_manager/index.html', context)

Here, fd is the query 'date' received from body. By default, items contains all the items present in the list. Now I just want the list of objects which have item.date==fd, how can I achieve that?

2 Answers

You can filter the data by using this code:

items = userlist.item_set.filter(date=request.POST.get("date"))

You can use request.POST[Django-Docs] instead of using json module to load the request body. If request.POST.get("date") is not a datetime object but a string then you'd need to parse it to datetime object using datetime.strptime().

def listView(request):
    if request.user.is_authenticated:
        fd = None
        user_id = request.user.id
        userlist, created = userList.objects.get_or_create(user_id=user_id)
        items = userlist.item_set.filter(date=request.POST.get("date"))
    else:
        items = None

    context = {"items": items}
    return render(request, "list_manager/index.html", context)
Related