Ganesh Mohanty
Ganesh Mohanty

Reputation: 289

How can i get username insted of userid?

model.py 
class Review(models.Model):
    user = models.ForeignKey(User,on_delete=models.CASCADE)
    product = models.ForeignKey(Product,on_delete=models.CASCADE)
    review = models.CharField(max_length=500)
    date_reviewed = models.DateTimeField(auto_now_add=True)

views.py
def review(request):
    if request.method=="POST":
        if request.user.is_authenticated:
            sender = request.user
            review=request.POST['review']
            pid = request.POST['pid']
            product=Product.objects.get(id=pid)
            
            
            rev = Review(user=sender,product=product,review=review)
            rev.save()
            reviews = Review.objects.filter(product=pid).values()
            
            da=list(reviews)
            print(da)
            return JsonResponse({'reviews':da})

Expected output:

[{'id': 6, 'user_name': sandeep, 'product_id': 2, 'review': 'lknkk',
 'date_reviewed': datetime.datetime(2021, 5, 1, 13, 2, 12, 404779, tzinfo=<UTC>)}]

I am trying send this data to my frontend using jsonresponse to create a product review table but in the output i am getting user_id insted of user_name .is there any way to pass user_name?
Here is actual output:

[{'id': 6, 'user_id': 2, 'product_id': 2, 'review': 'lknkk',
 'date_reviewed': datetime.datetime(2021, 5, 1, 13, 2, 12, 404779, tzinfo=<UTC>)}]

Upvotes: 0

Views: 63

Answers (1)

Razenstein
Razenstein

Reputation: 3717

e.g by modifying the query to explicitly add the user->username:

reviews = Review.objects.filter(product=pid).values('id','user__username','product', .... )

if you want to set an alias use F():

reviews = Review.objects.filter(product=pid).values('id',user_name=F('user__username'),'product', .... )

pay attention to the double-underscore in 'user__name' to access the field in the related model.

Upvotes: 1

Related Questions