Django model cross reference issue - django-models

I'm having a problem with some models in django. I want to set up 2 Tables ( Table and Order ) like this:
Code
class Table(models.Model):
number = models.PositiveSmallIntegerField()
restaurant = models.ForeignKey(Restaurant, on_delete=models.CASCADE)
current_order = models.OneToOneField(Order, blank=True)
is_free = models.BooleanField(default=True)
def __str__(self):
return "Table " + str(self.number) + " - Restaurant " + str(self.restaurant)
class Order(models.Model):
table = models.ForeignKey(Table, on_delete=models.CASCADE)
orders = models.ManyToManyField(Dish, through='DishOrder')
def __str__(self):
return "Order " + self.id
Error
When tryng to makemigrations django block me because 'Order is not definied'.
I understand the problem but I can't move the Order class before Table class otherwise the error will be 'Table not definied'
How can I solve this?

Related

How to edit django sql3 data base to ensure there is a user with id of 1?

django.db.utils.IntegrityError: The row in table 'food_item' with primary key '1' has an invalid foreign key: food_item.user_name_id contains a value '1' that does not have a corresponding value in auth_user.id.
# code from models.py of my app
from django.db import models
from django.contrib.auth.models import User
# Create your models here.
class Item(models.Model):
def __str__(self): # this bit of code is written for become avilable the name of the items insted of id. in shell
return self.item_name
user_name = models.ForeignKey( User, on_delete = models.CASCADE, default = 1 )
item_name = models.CharField(max_length=200)
item_disc = models.CharField(max_length=200)
item_price = models.IntegerField()
item_image = models.CharField(max_length=500, default='')
the problem is : User.objects.get( pk = 1 ) and pk = 2 are not exist. I had deleted the user profile pk = 1 and 2 because I had forgotten the password. This meant django could't find the user with the id of 1 .
how to fix the issue ?

ValueError: invalid literal for int() with base 10: b ' '

I get that error when I am trying to add new columns to my LeaveRequest model and migrate changes to my DB(postgresql). Below is the code.
class LeaveRequest(models.Model):
employee = models.ForeignKey(Employee)
leave_type = models.ForeignKey(LeaveType, null=False)
reason = models.TextField(max_length=200)
created_at = models.DateTimeField(auto_now_add=True)
start_date = models.DateField()
return_date = models.DateField()
def __str__(self):
return str(self.leave_type.name)

Trouble getting a union query to work across different models in Wagtail

I'm using Wagtail, and I have two models that have some fields in common. I would like to get a query of the union of those common fields. Here are the models:
class VideoPage(Page):
image = models.ForeignKey("wagtailimages.Image", blank=False, null=True, related_name="+", on_delete=models.SET_NULL)
vimeo_id = models.CharField(max_length=25)
publish_date = models.DateField(null=False, blank=False, default=datetime.date.today)
category_name = models.CharField(max_length=100, null=False, blank=True, default="Videos")
pdf = models.ForeignKey('wagtaildocs.Document', null=True, blank=False, default=1, on_delete=models.SET_NULL, related_name='+')
class CustomerHubFile(models.Model):
CASESTUDY = 'Case Study'
DATASHEET = 'Data Sheet'
SOLUTIONBRIEF = 'Solution Brief'
CATEGORY = [
(CASESTUDY, _('Case Study')),
(DATASHEET, _('Data Sheet')),
(SOLUTIONBRIEF, _('Solution Brief')),
]
title = models.CharField(max_length=255)
pdf = models.ForeignKey('wagtaildocs.Document', null=True, blank=False, on_delete=models.SET_NULL, related_name='+')
image = models.ForeignKey("wagtailimages.Image", blank=False, null=True, related_name="+", on_delete=models.SET_NULL, help_text="The image for the PDF")
publish_date = models.DateField(null=False, blank=False)
category_name = models.CharField(max_length=100, null=False, blank=True, choices=CATEGORY, default=CASESTUDY, verbose_name="Category")
Then I'm trying to add a query that joins both of these models together and return it in the context. I can't use values() or value_list() because I need access to the models in the template in order to use the images. I'd think I should be able to do it using only() like this:
pdfs = CustomerHubFile.objects.all().only('title', 'image', 'publish_date', 'category_name')
videos = VideoPage.objects.all().only('title', 'image', 'publish_date', 'category_name')
records = pdfs.union(videos).order_by('-publish_date')
context["records"] = records
return context
Unfortunately, only() also gets the id, but it doesn't get them in the same order for both models, which messes up the JOIN, resulting in an error that says "UNION types integer and character varying cannot be matched". Here is the generated SQL:
(
SELECT "customer_hub_customerhubfile"."id",
"customer_hub_customerhubfile"."title",
"customer_hub_customerhubfile"."image_id",
"customer_hub_customerhubfile"."publish_date",
"customer_hub_customerhubfile"."category_name"
FROM "customer_hub_customerhubfile"
ORDER BY "customer_hub_customerhubfile"."publish_date" DESC
)
UNION (
SELECT "wagtailcore_page"."title",
"customer_hub_videopage"."page_ptr_id",
"customer_hub_videopage"."image_id",
"customer_hub_videopage"."publish_date",
"customer_hub_videopage"."category_name"
FROM "customer_hub_videopage"
INNER JOIN "wagtailcore_page"
ON ("customer_hub_videopage"."page_ptr_id" = "wagtailcore_page"."id")
ORDER BY "wagtailcore_page"."path" ASC
)
I tried specifying the id fields in the only() but it still doesn't get them in specified order. Is there any way to get the ids to return as the first column for both queries, or is there another way I can get this union to work?

Google App Engine Datastore - query with StructuredProperty in projection and filter

I have a couple ndb models looks like these:
class Product(ndb.Model):
manufacturer = ndb.StringProperty()
category = ndb.StringProperty()
price = ndb.FloatProperty()
class Customer(ndb.Model):
customerId = ndb.StringProperty()
name = ndb.StringProperty()
products = ndb.StructuredProperty(Product, repeated=True)
And I'd like to query based on 'manufacturer' and 'category' of the product he/she owns. So this query works as expected.
query = Customer.query(Customer.products == Product(manufacturer=data_json["product"]["manufacturer"],
category=data_json["product"]["category"]))
results= query.fetch()
However, I cannot get the "projection" to work along with this query. The following query simply returned nothing.
query = Customer.query(Customer.products == Product(manufacturer=data_json["product"]["manufacturer"],
category=data_json["product"]["category"]))
results= query.fetch(projection=[Customer.products.price])
But if I use the projection without the filter, the projection part works fine. The following query will return all entities but only the 'price' property
results= Customer.query().fetch(projection=[Customer.products.price])
Any thoughts? Thanks.
BTW, my queries were developed based on this article.
https://cloud.google.com/appengine/docs/standard/python/ndb/queries#filtering_structured_properties
The correct way of combining AND and OR operations in the ndb library is documented in NDB Client Library's documentation.
With the query below, you are performing an AND operation in the filter, so instead of this one, you should use the one I propose below, using ndb.AND().
# Your query
query = Customer.query(Customer.products == Product(manufacturer=data_json["product"]["manufacturer"], category=data_json["product"]["category"]))
# Query using ndb.AND
query = Customer.query(ndb.AND(Customer.products == Product(manufacturer=data_json["product"]["manufacturer"]), Customer.products == Product(category=data_json["product"]["category"])))
Also, it turns out that if you perform the filtering in multiple steps, the query also works:
# Your request
query = Customer.query(Customer.products == Product(manufacturer=data_json["product"]["manufacturer"], category=data_json["product"]["category"]))
results = query.fetch(projection=[Customer.products.price])
# Request performing filter in multiple steps
query = Customer.query(Customer.products == Product(category=data_json["product"]["category"]))
query1 = query.filter(Customer.products == Product(manufacturer=data_json["product"]["manufacturer"]))
results = query1.fetch(projection=[Customer.products.price])
You can use either of the proposed alternatives, although I would suggest using ndb.AND() as it minimizes the code and is also the best way to combine AND operations.
UPDATE with some code:
app.yaml
runtime: python27
api_version: 1
threadsafe: true
handlers:
- url: /.*
script: main.app
main.py
import webapp2
from google.appengine.ext import ndb
# Datastore Models
class Product(ndb.Model):
manufacturer = ndb.StringProperty()
category = ndb.StringProperty()
price = ndb.FloatProperty()
class Customer(ndb.Model):
customerId = ndb.StringProperty()
name = ndb.StringProperty()
products = ndb.StructuredProperty(Product, repeated=True)
# Create entities for testing purposes
class CreateEntities(webapp2.RequestHandler):
def get(self):
prod1 = Product(manufacturer="Google", category="GCP", price=105.55)
prod2 = Product(manufacturer="Google", category="GCP", price=123.45)
prod3 = Product(manufacturer="Google", category="Drive", price=10.38)
prod1.put()
prod2.put()
prod3.put()
cust1 = Customer(customerId="Customer1", name="Someone", products=[prod1,prod2,prod3])
cust2 = Customer(customerId="Customer2", name="Someone else", products=[prod1])
cust3 = Customer(customerId="Customer3", name="Noone", products=[prod3])
cust1.put()
cust2.put()
cust3.put()
# Response text
self.response.headers['Content-Type'] = 'text/plain'
self.response.write('Done creating entities')
class GetEntities(webapp2.RequestHandler):
def get(self):
# This will not work
#query = Customer.query(Customer.products == Product(category="GCP", manufacturer="Google"))
#results = query.fetch(projection=[Customer.products.price])
# Alternative 1 - WORKS
#query = Customer.query(Customer.products == Product(category="GCP"))
#query1 = query.filter(Customer.products == Product(manufacturer="Google"))
#results = query1.fetch(projection=[Customer.products.price])
# Alternative 2 - WORKS
query = Customer.query(ndb.AND(Customer.products == Product(manufacturer="Google"), Customer.products == Product(category="GCP")))
results = query.fetch(projection=[Customer.products.price])
self.response.out.write('<html><body>')
for result in results:
self.response.out.write("%s<br><br>" % result)
self.response.out.write('</body></html>')
app = webapp2.WSGIApplication([
('/createEntities', CreateEntities),
('/getEntities', GetEntities),
], debug=True)

django postgresql insert or update on table violates foreign key constraint

I'm getting the error message:
insert or update on table "quizzer_progress" violates foreign key
constraint. DETAIL: Key (word_id)=(4700) is not present in table
"quizzer_alone_words".
but it makes no sense.
I have these 3 tables in models.py:
class Progress(models.Model):
success = models.IntegerField(default=0)
fail = models.IntegerField(default=0)
total = models.IntegerField(default=0)
word = models.ForeignKey(Word, related_name='word_progress', blank=True, null=True)
class WordLesson(models.Model):
text = models.CharField(max_length=3000, blank=True)
owner = models.ForeignKey(User, related_name='Words_from_lessons')
words = models.ManyToManyField('Alone_Words', blank=True)
min_age = models.IntegerField(default=0)
max_age = models.IntegerField(default=0)
class Alone_Words(models.Model):
lesson = models.ForeignKey(WordLesson, related_name='lesson_of_the_word', blank=True, default=1)
word = models.CharField(max_length=100, blank=True)
position = models.IntegerField(default=0)
As you can see, the table where I'm trying to save data has nothing to do with the one that "violates foreign key constraint"
Anyone can tell me what's happening????
NOTE: the code failing is this one ->
p = Progress(success =0,fail = 0,total =0,word = myword)
p.save()

Resources