How to access using foreing key

33 views
Skip to first unread message

Ashutosh Mishra

unread,
Oct 30, 2020, 11:52:59 AM10/30/20
to Django users
class User(models.Model):
name=models.CharField(max_length=50,blank=True,null=True)
latitude = models.CharField('Latitude', max_length=30, blank=True, null=True)
longitude = models.CharField('Longitude', max_length=30, blank=True, null=True)
location = models.PointField(blank=True, null=True)

def __str__(self):
return str(self.name)

class Restaurant(models.Model):
restaurant_name=models.CharField(max_length=50,blank=True,null=True)
latitude = models.CharField('Latitude', max_length=30, blank=True, null=True)
longitude = models.CharField('Longitude', max_length=30, blank=True, null=True)
location = models.PointField(blank=True, null=True)

def __str__(self):
return str(self.restaurant_name)


class RestaurantRating(models.Model):
user = models.ForeignKey(User,on_delete=models.CASCADE,null=True,related_name="customer_rating")
restaurant = models.ForeignKey(Restaurant, on_delete=models.CASCADE, null=True, related_name="rating_restaurant")
rating = models.FloatField()

def __str__(self):
return str(self.user)

How can i filter the restaurants whose rating is 5,Restaurant.objects.filter()

David Nugent

unread,
Oct 31, 2020, 11:33:39 PM10/31/20
to django...@googlegroups.com, Ashutosh Mishra
Restaurant.objects.filter(rating_restaurant=5.0)

Regards
/d

Peter of the Norse

unread,
Dec 13, 2020, 10:19:30 PM12/13/20
to django...@googlegroups.com
If you are looking for all of the Restaurants with a 5.0 rating, it looks like

Restaurant.objects.filter(rating_restaurant__rating = 5.0)

If you are looking for Restaurants with an average rating of 5.0, that’s a bit trickier.

from django.db.models import Avg
Restaurant.objects.annotate(avg_rating = Avg('rating_restaurant__rating')).filter(avg_rating__eq = 5.0)


--
You received this message because you are subscribed to the Google Groups "Django users" group.
To unsubscribe from this group and stop receiving emails from it, send an email to django-users...@googlegroups.com.
To view this discussion on the web visit https://groups.google.com/d/msgid/django-users/cdaa9adf-5b4e-4de7-9c9d-f9e875e17acbn%40googlegroups.com.

Reply all
Reply to author
Forward
0 new messages