django error (no such column: projects_review.project_id) - python

I can't open my Review table, here's the models of code:
This is the `Project` model:
class Project(models.Model):
title = models.CharField(max_length=200)
description = models.TextField(null=True, blank=True)
demo_link = models.CharField(max_length=2000, null=True, blank=True)
source_link = models.CharField(max_length=2000, null=True, blank=True)
tags = models.ManyToManyField('Tag', blank=True)
vote_total = models.IntegerField(default=0, null=True, blank=True)
vote_ratio = models.IntegerField(default=0, null=True, blank=True)
created = models.DateTimeField(auto_now_add=True)
id = models.UUIDField(default=uuid.uuid4, unique=True,
primary_key=True, editable=False)
def __str__(self):
return self.title
And this is the Review model:
class Review(models.Model):
VOTE_TYPE = (
('up', 'Up Vote'),
('down', 'Down Vote'),
)
project = models.ForeignKey(Project, on_delete=models.CASCADE)
body = models.TextField(null=True, blank=True)
value = models.CharField(max_length=200, choices=VOTE_TYPE)
created = models.DateTimeField(auto_now_add=True)
id = models.UUIDField(default=uuid.uuid4, unique=True,primary_key=True, editable=False)
def __str__(self):
return self.title
but I can't open my Review table on admin panel (OperationalError at /admin/projects/review/)
Here's the error details:
I make migrations and do migrate:

Related

Serialize same level object from Many to many field

I have to serialize spare instance from spare variety many to many field.
Models.py
class SpareVariety(models.Model):
quality = models.ForeignKey(Quality, max_length=255, on_delete=models.CASCADE, null=True, blank=True)
variety_name = models.CharField(max_length=255, null=True, blank=True)
property = models.ForeignKey(SpareProperty, null=True, blank=True, on_delete=models.CASCADE)
purchase_price = models.PositiveIntegerField(help_text="in INR", blank=True, null=True)
retail_price = models.FloatField(help_text="All values in INR", blank=True, null=True)
dealer_price = models.FloatField(help_text="All values in INR", blank=True, null=True)
stock_available = models.PositiveIntegerField(blank=True, null=True,default=True)
spare_costing = models.ForeignKey(SpareCosting, on_delete=models.CASCADE, blank=True, null=True)
spare_discount = models.ForeignKey(Discount, on_delete=models.CASCADE, blank=True, null=True)
is_available = models.BooleanField(default=False)
date_added = models.DateTimeField(auto_now=True)
date_updated = models.DateTimeField(auto_now_add=True)
class Spare(models.Model):
product = models.ForeignKey(Product, on_delete=models.CASCADE)
spare_variety = models.ManyToManyField(SpareVariety, related_name='spare_varieties', null=True, blank=True)
name = models.CharField(max_length=255, help_text="Enter the name of spare (Ex:Display, Speakers)")
type = models.ForeignKey(Type, blank=True, null=True, on_delete=models.CASCADE)
date_added = models.DateTimeField(auto_now=True)
date_updated = models.DateTimeField(auto_now_add=True)
def __str__(self):
return '%s - %s' % (self.product.name, self.name)
Serialize the spare model from spare variety serializer
serializers.py
class SpareVarietySerializer(serializers.HyperlinkedModelSerializer):
spare_costing= SpareCostingSerializer(many=False, read_only=False)
spare_discount = DiscountSerializer(many=False, read_only=False)
quality = QualitySerializer(many=False, read_only=False)
property = SparePropertySerializer(many=False, read_only=False)
spare_name = serializers.CharField(read_only=True, source="spare.name")
class Meta:
model = SpareVariety
fields = ['id','quality','variety_name','purchase_price','spare_name','retail_price','property', 'dealer_price', 'stock_available','spare_costing','spare_discount','is_available', 'date_added', 'date_updated',]

How to count reviews for a product in django?

I am building an ecommerce website with django. In my models I have a Product and review model. How should i connect the two for the number of reviews and average rating attribute?
This is my current models file
class Product(models.Model):
name = models.CharField(max_length=200, null=True, blank=True)
brand = models.CharField(max_length=200, null=True, blank=True)
image = models.ImageField(null=True, blank=True, default='placeholder.png')
description = models.TextField(null=True, blank=True)
rating = models.DecimalField(max_digits=7, decimal_places=2, null=True, blank=True)
price = models.DecimalField(max_digits=7, decimal_places=2, null=True, blank=True)
countInStock = models.IntegerField(null=True, blank=True, default=0)
id = models.UUIDField(default=uuid.uuid4, max_length=36, unique=True, primary_key=True, editable=False)
numReviews = [Count the number of reviews where product.id matches self.id]
averageRating = [Sum up the ratings in reviews for this product and divide them by their count]
def __str__(self):
return str(self.name)
class Review(models.Model):
product = models.ForeignKey(Product, on_delete=models.SET_NULL, null=True)
user = models.ForeignKey(User, on_delete=models.SET_NULL, null=True)
rating = models.IntegerField(null=True, blank=True, default=0)
comment = models.TextField(null=True, blank=True)
createdAt = models.DateTimeField(auto_now_add=True)
id = models.UUIDField(default=uuid.uuid4, max_length=36, unique=True, primary_key=True, editable=False)
def __str__(self):
return f'{self.user} review for {self.product}'
As you can see the numReviews and average rating columns are meant to connect both tables. I have been trying to figure out how to do it correctly with no success.
Any help would be greatly appreciated
I would make them into model methods.. I don't think there will be any issues that the Review object is defined below the method
and for the Avg I used a Django command aggregate which forces the DB to do the work.
models.py
class Product(models.Model):
name = models.CharField(max_length=200, null=True, blank=True)
brand = models.CharField(max_length=200, null=True, blank=True)
image = models.ImageField(null=True, blank=True, default='placeholder.png')
description = models.TextField(null=True, blank=True)
rating = models.DecimalField(max_digits=7, decimal_places=2, null=True, blank=True)
price = models.DecimalField(max_digits=7, decimal_places=2, null=True, blank=True)
countInStock = models.IntegerField(null=True, blank=True, default=0)
id = models.UUIDField(default=uuid.uuid4, max_length=36, unique=True, primary_key=True, editable=False)
def __str__(self):
return str(self.name)
def num_of_reviews(self):
return Review.objects.filter(product=self).count()
def average_rating(self):
from django.db.models import Avg
return Review.objects.filter(product=self).aggregate(Avg('rating'))['rating__avg']
Use
obj = Product.objects.all().first()
obj.num_of_reviews()
obj.average_rating()
Edit
Reverse relationship per #NixonSparrow
def num_of_reviews(self):
return self.review_set.count()
def average_rating(self):
from django.db.models import Avg
return self.review_set.aggregate(Avg('rating'))['rating__avg']

Django Rest API: Serializer won't show Foreign Key Field values

I'm trying to list the values of FacilityAddressSerializer within the FacilitySearchSerializer. This is what i tried. I get all the values of the FacilitySearchSerializer but the values of the FacilityAddressSerializer are showing as Null:
serializers.py
class FacilityAddressSerializer(serializers.ModelSerializer):
class Meta:
model = FacilityAddress
fields = (
"id",
"PrimaryAddress",
"SecondaryAddress",
"City",
"RegionOrState",
"PostalCode",
"Geolocation",
"AddressInfo"
)
class FacilitySearchSerializer(serializers.ModelSerializer):
AddressInfo = FacilityAddressSerializer(source="fa")
class Meta:
model = Facility
fields = (
"id",
"Name",
"AddressInfo",
"ListingVerified",
"mainimage",
"AdministratorCell",
"Capacity",
"PriceRangeMin",
"PriceRangeMax",
)
read_only_fields = ("id", "Name", "ListingVerified", "mainimage", "AdministratorCell", "Capacity", "FeaturedVideo", "PriceRangeMin", "PriceRangeMax")
models.py
class Facility(models.Model):
Name = models.CharField(max_length=150, null=True, blank=False)
mainimage = models.ImageField(null=True, blank=True)
Capacity = models.IntegerField(null=True, blank=True)
TelephoneNumber = models.CharField(max_length=30, null=True, blank=True)
AdministratorCell = PhoneNumberField(null=True, blank=True)
PriceRangeMin = models.IntegerField(null=True, blank=True)
PriceRangeMax = models.IntegerField(null=True, blank=True)
class FacilityAddress(models.Model):
PrimaryAddress = models.CharField(max_length=150, null=True, blank=True)
SecondaryAddress = models.CharField(max_length=150, null=True, blank=True)
City = models.CharField(max_length=150, null=True, blank=True)
RegionOrState = models.CharField(max_length=50, null=True, blank=True)
PostalCode = models.CharField(max_length=30, null=True, blank=True)
Geolocation = models.CharField(max_length=30, null=True, blank=True)
AddressInfo = models.ForeignKey(Facility, null=True, blank=True, on_delete=models.CASCADE, related_name='fa')
It works after i added (many=True) next to the source=fa. I thought i didn't need that since i'm using foreign key fields and not manytomany fields but i guess i was wrong.

Find pk in queryset Django

I have a problem in obtaining a single id from a queryset. I post my models and views in order to be more clear:
models.py
class MissionEntry(models.Model):
student = models.ForeignKey(
Student, on_delete=models.DO_NOTHING, blank=True, null=True)
mission = models.ForeignKey(
Mission, on_delete=models.DO_NOTHING, null=True, blank=True)
log_entry = models.ForeignKey(
LogEntry, on_delete=models.DO_NOTHING, blank=True, null=True)
learning_objective = models.ForeignKey(
LearningObjective, on_delete=models.DO_NOTHING, blank=True, null=True)
grade = models.CharField(
max_length=10, choices=GRADING_VALUE, blank=True, null=True)
note = models.TextField(blank=True, null=True)
debriefing = models.TextField(blank=True, null=True)
created_at = models.DateTimeField(auto_now_add=True)
updated_at = models.DateTimeField(auto_now=True)
def __str__(self):
return str(self.mission) + ' ' + str(self.log_entry)
class Meta:
verbose_name_plural = 'Mission Entries'
class MissionEntryStatus(models.Model):
mission = models.ForeignKey(
Mission, on_delete=models.PROTECT, null=True, blank=True)
student = models.ForeignKey(Student, on_delete=models.PROTECT)
is_completed = models.BooleanField(default=False)
is_failed = models.BooleanField(default=False)
created_at = models.DateTimeField(auto_now_add=True)
updated_at = models.DateTimeField(auto_now=True)
class StudentMission(models.Model):
mission = models.ForeignKey(Mission, on_delete=models.PROTECT)
student_training_course = models.ForeignKey(
StudentTrainingCourse, on_delete=models.PROTECT)
mission_status = models.ForeignKey(
MissionEntryStatus, on_delete=models.PROTECT, blank=True, null=True)
created_at = models.DateTimeField(auto_now_add=True)
updated_at = models.DateTimeField(auto_now=True)
class Meta:
ordering = ['mission__name']
def __str__(self):
return self.mission.name
class LogEntry(models.Model):
aircraft = models.ForeignKey(Aircraft, on_delete=models.DO_NOTHING)
adep = models.ForeignKey(
Aerodrome, on_delete=models.PROTECT, related_name='adep')
ades = models.ForeignKey(
Aerodrome, on_delete=models.PROTECT, related_name='ades')
date = models.DateField()
etd = models.TimeField()
ata = models.TimeField()
eet = models.TimeField()
function_type = models.ForeignKey(FunctionType, on_delete=models.PROTECT)
student = models.ForeignKey(
Student, on_delete=models.PROTECT, blank=True, null=True)
instructor = models.ForeignKey(
Instructor, on_delete=models.PROTECT, blank=True, null=True)
student_mission = models.ForeignKey(
'mission.StudentMission', on_delete=models.PROTECT, null=True, blank=True)
note = models.TextField(null=True, blank=True)
cross_country = models.BooleanField(default=False)
created_at = models.DateTimeField(auto_now_add=True)
updated_at = models.DateTimeField(auto_now=True)
views.py
def student_mission_list(request, pk):
student = Student.objects.get(id=pk)
student_training_course = StudentTrainingCourse.objects.filter(
student_id=student.id)
missions = StudentMission.objects.filter(
student_training_course_id__in=student_training_course)
mission_entry = MissionEntry.objects.filter(student_id=student)
log_entry = LogEntry.objects.filter(student_mission_id__in=missions)
print(log_entry)
context = {
'student': student,
'missions': missions,
'mission_entry': mission_entry,
}
return render(request, 'mission/student_mission_list.html', context)
In fact, what I need to do, is to obtain a single value for the log_entry. The problem is that, obviously, I am retrieving multiple values of log_entry. But I would like to get the single pk of the log_entry.
Any suggestion? Should I remodel the models.py file?
try this:
log_entry = LogEntry.objects.get(student_mission_id__in=missions)
print(log_entry.id)

ValueError: save() prohibited to prevent data loss due to unsaved related object

Hi I am recreating a website in django and this happens...
Django throw this error,
ValueError: save() prohibited to prevent data loss due to unsaved related object 'fk_deal'.
even though I have saved the foreign key related object. This is the view part.
if request.method == "POST":
deal = DEAL()
name = request.POST.get('name')
revenue_2013 = request.POST.get('revenue_2013')
if project_name:
print project_name
deal.name = project_name
deal.save()
print deal.id # prints None
# financials 2013
if revenue_2013:
fin = DEALFINANCIALINFORMATION.objects.create(
financial_category_amount=revenue_2013,
financial_year='2013',
fk_deal = deal,
financial_category_id=1,
)
These are the models....
class DEAL(models.Model):
id = models.BigIntegerField(db_column='ID', primary_key=True) # Field name made lowercase.
company_name = models.CharField(max_length=33L, db_column=u'COMPANY_NAME', blank=True)
investmentrequired = models.FloatField(null=True, blank=True)
is_deleted = MySQLBooleanField(db_column=u'IS_DELETED', blank=True, default=None)
name = models.CharField(max_length=33L, db_column=u'NAME', blank=True)
photo = models.CharField(max_length=66L, db_column=u'PHOTO', blank=True)
status = models.CharField(max_length=85L, db_column=u'STATUS', blank=True)
timestamp = models.DateTimeField(null=True, db_column=u'TIMESTAMP', blank=True)
teaser = models.TextField(db_column=u'TEASER', blank=True)
currency_id = models.BigIntegerField(null=True, db_column=u'CURRENCY_ID', blank=True)
description = models.TextField(db_column=u'DESCRIPTION', blank=True)
country = models.ForeignKey('COUNTRIES', null=True, db_column=u'COUNTRY_ID', blank=True)
sector = models.ForeignKey('SECTORS', null=True, db_column=u'SECTOR_ID', blank=True)
type = models.ForeignKey('TYPES', null=True, db_column=u'TYPE_ID', blank=True)
username = models.CharField(max_length=85L, db_column=u'USERNAME', blank=True)
user = models.ForeignKey('USER', null=True, db_column=u'USER_ID', blank=True)
hitcounter = models.BigIntegerField(null=True, db_column=u'HITCOUNTER', blank=True)
approx_usd = models.DecimalField(decimal_places=2, null=True, max_digits=19, db_column=u'approxUSD', blank=True)
userdeal_id = models.BigIntegerField(null=True, db_column=u'USERDEAL_ID', blank=True)
is_featuredeal = MySQLBooleanField(db_column=u'IS_FEATUREDEAL', blank=True, default=None)
basic_company_email = models.CharField(max_length=33L, db_column=u'BASIC_COMPANY_EMAIL', blank=True)
basic_company_name = models.CharField(max_length=33L, db_column=u'BASIC_COMPANY_NAME', blank=True)
basic_company_phone = models.CharField(max_length=33L, db_column=u'BASIC_COMPANY_PHONE', blank=True)
basic_company_website = models.CharField(max_length=33L, db_column=u'BASIC_COMPANY_WEBSITE', blank=True)
basic_elevator_pitch = models.TextField(db_column=u'BASIC_ELEVATOR_PITCH', blank=True)
basic_premoney_evaluation = models.DecimalField(decimal_places=2, null=True, max_digits=19, db_column=u'BASIC_PREMONEY_EVALUATION', blank=True)
basic_question_1 = models.TextField(db_column=u'BASIC_QUESTION_1', blank=True)
basic_question_2 = models.TextField(db_column=u'BASIC_QUESTION_2', blank=True)
basic_question_3 = models.TextField(db_column=u'BASIC_QUESTION_3', blank=True)
basic_summary = models.TextField(db_column=u'BASIC_SUMMARY', blank=True)
basic_total_offering_amount = models.DecimalField(decimal_places=2, null=True, max_digits=19, db_column=u'BASIC_TOTAL_OFFERING_AMOUNT', blank=True)
is_company = MySQLBooleanField(db_column=u'IS_COMPANY', blank=True, default=None)
is_posted = MySQLBooleanField(db_column=u'IS_POSTED', blank=True, default=None)
is_visible = MySQLBooleanField(db_column=u'IS_VISIBLE', blank=True, default=None)
other_company_milestones = models.TextField(db_column=u'OTHER_COMPANY_MILESTONES', blank=True)
projectname = models.CharField(max_length=33L, db_column=u'PROJECTNAME', blank=True)
basicdealstage = models.ForeignKey('DEALSTAGES', null=True, db_column=u'BASICDEALSTAGE_ID', blank=True)
basic_security_type = models.ForeignKey('SECURITYTYPES', null=True, db_column=u'BasicSecurityType_ID', blank=True)
is_public = MySQLBooleanField(db_column=u'IS_PUBLIC', blank=True, default=None)
profile_completed = models.BigIntegerField(null=True, db_column=u'PROFILE_COMPLETED', blank=True)
is_closed = MySQLBooleanField(db_column=u'IS_CLOSED', blank=True, default=None)
first_step_completed = models.BigIntegerField(null=True, db_column=u'FIRST_STEP_COMPLETED', blank=True, default=0L)
second_step_completed = models.BigIntegerField(null=True, db_column=u'SECOND_STEP_COMPLETED', blank=True)
third_step_completed = models.BigIntegerField(null=True, db_column=u'THIRD_STEP_COMPLETED', blank=True)
class Meta:
db_table = u'DEAL'
def __unicode__(self):
if self.name:
return self.name
else:
return "No name"
class DEALFINANCIALINFORMATION(models.Model):
id = models.BigIntegerField(db_column='ID', primary_key=True) # Field name made lowercase.
financial_category_amount = models.DecimalField(decimal_places=2, null=True, max_digits=19, db_column=u'FINANCIAL_CATEGORY_AMOUNT', blank=True)
financial_year = models.CharField(max_length=33L, db_column=u'FINANCIAL_YEAR', blank=True)
de_al_id = models.BigIntegerField(null=True, db_column=u'DEAl_ID', blank=True)
financial_category_id = models.BigIntegerField(null=True, db_column=u'FINANCIAL_CATEGORY_ID', blank=True)
fk_deal = models.ForeignKey('DEAL', null=True, blank=True)
class Meta:
db_table = u'DEAL_FINANCIAL_INFORMATION'
The database was created from an existing MySQL database....
I send the data to the view using jquery POST....
I can't seem to find out what the problem is. Also even after saving the model if I print the id field it returns None instead....
Can somebody help me?

Categories

Resources