I have a model:
from django.db import models
class Author(models.Model):
name = models.CharField(max_length=100)
age = models.IntegerField()
class Publisher(models.Model):
name = models.CharField(max_length=300)
num_awards = models.IntegerField()
class Book(models.Model):
name = models.CharField(max_length=300)
pages = models.IntegerField()
price = models.DecimalField(max_digits=10, decimal_places=2)
rating = models.FloatField()
authors = models.ManyToManyField(Author)
publisher = models.ForeignKey(Publisher)
pubdate = models.DateField()
class Store(models.Model):
name = models.CharField(max_length=300)
books = models.ManyToManyField(Book)
registered_users = models.PositiveIntegerField()
I could not understand how the following code work
This is from the django official Documentation, in the cheat sheet.
https://docs.djangoproject.com/en/1.10/topics/db/aggregation/
What I am trying to do is count the total votes for the following model
I use Question.objects.filter(owner_id=1).annotate(total_votes=Sum('votes')) as in the documentation. But this not work for me.
class Question(models.Model):
question_text = models.CharField('Question',max_length=200)
pub_date = models.DateTimeField('date published')
owner = models.ForeignKey(User,default=DEFAULT_USER_ID)
class Choice(models.Model):
question = models.ForeignKey(Question, on_delete=models.CASCADE)
choice_text = models.CharField(max_length=200)
votes = models.IntegerField(default=0)
Your Question model doesn't have votes your Choice model does
Question.objects.filter(owner_id=1).annotate(total_votes=Sum('choice__votes'))
Related
I got this code, but I can't find a way to create a view that retrieve the allergies a patient has.
class Patient(models.Model):
user = models.OneToOneField(User, related_name='patient', on_delete=models.CASCADE)
id_type = models.CharField(max_length=300)
id_number = models.CharField(max_length=300)
creation_date = models.DateField(default=datetime.date.today)
class Allergie(models.Model):
name = models.CharField(max_length=300, default="X")
class PatientAllergies(models.Model):
patient = models.ForeignKey(Patient, related_name="patient_allergies", on_delete=models.CASCADE)
allergie = models.ForeignKey(Allergie, on_delete=models.CASCADE, null=True)
professional_contract = models.ForeignKey(ProfessionalContract, null=True ,on_delete=models.CASCADE)
You can span a ManyToManyField relation over your PatientAllergies model that acts as a junction table:
class Patient(models.Model):
user = models.OneToOneField(User, related_name='patient', on_delete=models.CASCADE)
id_type = models.CharField(max_length=300)
id_number = models.CharField(max_length=300)
creation_date = models.DateField(auto_now_add=True)
allergies = models.ManyToManyField(
'Allergie',
through='PatientAllergies'
)
# …
You can then for a Patient object p with:
p.allergies.all()
An alternative is to filter the Allergie objects with:
Allergie.objects.filter(patientallergies__patient=p)
or with the ManyToManyField:
Allergie.objects.filter(patient=p)
In Models:
class ShopCategory(models.Model):
category = models.CharField(max_length=100)
class Meta:
db_table = "tbl_ShopCategory"
class Shop(models.Model):
id_shop = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
name = models.CharField(max_length=200)
slug = models.SlugField(max_length=250, blank=True, null=True)
cover_img = models.CharField(max_length=250, blank=True)
category = models.ForeignKey(ShopCategory, on_delete=models.CASCADE)
avgscore = models.FloatField(default=0)
I want to show the Category name?
...........................................................
Add an str method to your ShopCategory model:
class ShopCategory(models.Model):
category = models.CharField(max_length=100)
def __str__(self):
return self.category
class Meta:
db_table = "tbl_ShopCategory"
I am having an issue with 2 Foreign Key assignments in my django model. See models.py below:
from django.db import models
from django.contrib.auth.models import User
class userData(models.Model):
user = models.ForeignKey(User)
house = models.CharField(max_length=100)
address = models.CharField(max_length=100, blank=True, null=True)
street = models.CharField(max_length=150)
state = models.CharField(max_length=100)
postcode = models.CharField(max_length=20)
country = models.CharField(max_length=100)
telephone = models.CharField(max_length=20)
subscription = models.IntegerField(default=0)
active = models.IntegerField(default=0)
class area(models.Model):
area_name = models.CharField(max_length=100)
longitude = models.CharField(max_length=100)
latitude = models.CharField(max_length=100)
class country(models.Model):
area_name = models.CharField(max_length=100)
longitude = models.CharField(max_length=100)
latitude = models.CharField(max_length=100)
class city(models.Model):
area_name = models.CharField(max_length=100)
longitude = models.CharField(max_length=100)
latitude = models.CharField(max_length=100)
class foodType(models.Model):
food_type_name = models.CharField(max_length=100)
class restaurant(models.Model):
restaurant_name = models.CharField(max_length=100)
food_type = models.ForeignKey(foodType)
area = models.ForeignKey(area)
country = models.ForeignKey(country)
city = models.ForeignKey(city)
date_added = models.DateField()
main_image = models.ImageField(blank=True, null=True)
website = models.URLField(blank=True, null=True)
summary = models.TextField(blank=True, null=True)
description = models.TextField(blank=True, null=True)
featured = models.IntegerField(default=0)
class restaurantFeature(models.Model):
feature_name = models.CharField(max_length=100)
restaurant_id = models.ForeignKey(restaurant)
Django Foreign Key not working correctly
The image shows the Country and City, not showing correctly, like the FoodType and Area does. Theses show with the + buttons for adding, the mysql database is showing the key next to the fields. I have also tried renaming country and City adding Location after, thinking it could be something with these names.
Appreciate any help with this one.
You're having this issue because you need to reference ALL the models inside the admin.py. Django admin doesn't know what you're referencing.
In the following example from django documentation, how to get
Publisher.objects.all()
annotated with field average_rating computed using average of book ratings and max_rating computed using maximum rating of books?
from django.db import models
class Author(models.Model):
name = models.CharField(max_length=100)
age = models.IntegerField()
class Publisher(models.Model):
name = models.CharField(max_length=300)
num_awards = models.IntegerField()
class Book(models.Model):
name = models.CharField(max_length=300)
pages = models.IntegerField()
price = models.DecimalField(max_digits=10, decimal_places=2)
rating = models.FloatField()
authors = models.ManyToManyField(Author)
publisher = models.ForeignKey(Publisher)
pubdate = models.DateField()
class Store(models.Model):
name = models.CharField(max_length=300)
books = models.ManyToManyField(Book)
registered_users = models.PositiveIntegerField()
Precisely I should be able to print something like this after the queryset:
for p in Publisher.objects.all().annotate(...):
print p, p.average_rating, p.max_rating
You can access books of publisher using book__rating like this:
Publisher.objects.annotate(average_rating=Avg('book__rating'), max_rating=Max('book__rating'))
I have three model:
class Category(models.Model):
category_name = models.CharField(max_length=128, unique=True)
category_alias = models.CharField(max_length=128, unique=True)
category_desc = models.TextField()
class Question(models.Model):
user = models.ForeignKey(User)
category = models.ForeignKey(Category)
question_text = models.CharField(max_length=200)
pub_date = models.DateTimeField(auto_now=True)
is_approved = models.BooleanField(default=0)
class Answer(models.Model):
user = models.ForeignKey(User)
question = models.ForeignKey(Question)
answer = models.TextField()
is_approved = models.BooleanField(default=0)
class Rating(models.Model):
user = models.ForeignKey(User)
answer = models.ForeignKey(Answer)
rating = models.BooleanField(default=0)
I need a query which will find most liked answer(Answer which have most ratings) with its question and rating for a particular category. This mean if answer 2 have most ratings therefore i will get object for that answer with related question and ratings for any particular category.
class Rating(models.Model):
user = models.ForeignKey(User)
answer = models.ForeignKey(Answer)
rating = models.BooleanField(default=0, related_name='rating')
answers = Answer.objects.filter(question__category__id=category_id).annotate(
rating_sum=Count(rating__rating)).order_by('-rating_sum')
You should use 'annotate' method to count positive marks and arrange answers by this field.