Django doesn't see fk in other table - python

I have some models and fk on them to others.
models.py
class ElementMessages(models.Model)
element = models.ForeignKey(Element, on_delete=models.CASCADE)
sender = models.ForeignKey(UserAccount, on_delete=models.SET_NULL, null=True)
text = models.TextField(max_length=512, null=True)
send_time = models.DateTimeField(auto_now_add=True)
type = models.CharField(max_length=16, choices=MESSAGE_TYPES, default=SIMPLE)
type_dialog = models.CharField(max_length=10, choices=DIALOG_TYPE, default=DIALOG_TALK)
request = models.ForeignKey(ChatRequest, null=True, default=None, on_delete=models.CASCADE)
post_work = models.ForeignKey(PostWork, null=True, default=None, on_delete=models.CASCADE)
files = models.BooleanField(default=False)
class Element(models.Model):
id = models.UUIDField(default=uuid.uuid4, editable=False, unique=True, primary_key=True)
artist = models.ForeignKey(Artist, on_delete=models.CASCADE, related_name='chat_element', null=True, blank=True)
customer = models.ForeignKey(Customer, on_delete=models.CASCADE, related_name='chat_element', null=True, blank=True)
element = models.ForeignKey('projects.Element', null=False, on_delete=models.CASCADE, related_name='chat_element')
When I try to delete Element object, it raises this:
django.db.utils.IntegrityError: insert or update on table "chat_elementmessages" violates foreign key constraint "chat_elementmessages_element_id_672e2ba2_fk_chat_element_id"
DETAIL: Key (element_id)=(87cdd8d7-47f0-4264-8aa7-ae21a8246fd8) is not present in table "chat_element".
But when I look at table in db, this key exists.
How to fix that?

As it turned out, problems were at Django pre_delete andpost_delete signals. They tried to refer to a non-existing object, that I'm try to delete. Fixed with simple check on the existence of the object.

Related

django.db.utils.IntegrityError: The row in table 'accountss_comments' with primary key '10' has an invalid foreign key

I'm trying to make the patient give a review and a rate but this error pop up when I run migrate
the error is
django.db.utils.IntegrityError: The row in table 'accountss_comments' with primary key '10' has an invalid foreign key: accountss_comments.doctore_id contains a value '1' that does not have a corresponding value in accountss_doctor.user_id.
this my models
class User(AbstractUser):
is_doctor = models.BooleanField(default=False)
is_patient = models.BooleanField(default=False)
class Doctor(models.Model):
user = models.OneToOneField(
User, on_delete=models.CASCADE, primary_key=True)
number_phone = models.CharField(
_('االهاتف :'), max_length=50, blank=True, null=True)
class Patient(models.Model):
user = models.OneToOneField(
User, on_delete=models.CASCADE, primary_key=True)
name = models.CharField(max_length=50, verbose_name="الاسم ")
class Comments(models.Model):
created_by = models.ForeignKey(
Patient, on_delete=models.CASCADE)
doctore = models.ForeignKey(
Doctor, on_delete=models.CASCADE, related_name='comments')
# co_email = models.ForeignKey(
# User, on_delete=models.CASCADE, related_name='comment')
co_body = models.TextField(max_length=400, verbose_name='التعليق')
rate = models.IntegerField(default=0)
created_dt = models.DateTimeField(auto_now_add=True)
active = models.BooleanField(default=True)
please if there is any solution write below and explain it because I'm still new to Django I tried so hard to fix but with no result

How to implement a database for storing parentId and a list of children?

I need to implement a POST request with data loading via two keys: "items" and "UpdateDate".
But in the database with items it is necessary to store the parent (parentId) of the category /product and a list of children (children).
and record the time from the "UpdateDate" key in the date field for all categories/products imported for this request
The screenshots below show a detailed TT.
I haven't been able to figure out how to implement a database on Django/Django Rest Framework for a week.
Screens:
class ShopUnit(models.Model):
id = models.UUIDField(primary_key=True, verbose_name='Unique identifier', default=uuid.uuid4, editable=False,
null=False)
name = models.CharField(max_length=255, verbose_name='Category/Product name', null=False)
date = models.ForeignKey('Date', on_delete=models.CASCADE, related_name='date', null=True, blank=True)
parentId = models.ForeignKey("self", on_delete=models.CASCADE, null=True, blank=True, related_name='сhilden',
db_index=True)
type = models.CharField(max_length=10, verbose_name='Element Type', choices=ShopUnitType.choices)
price = models.PositiveIntegerField(null=True, blank=True, verbose_name='Цена')
children = models.ForeignKey("self", null=True, blank=True, on_delete=models.SET_NULL, related_name='parent')
There are small developments:
https://i.stack.imgur.com/GdAaK.png
https://i.stack.imgur.com/fzBdS.png
https://i.stack.imgur.com/LRQIq.png
https://i.stack.imgur.com/tssis.png

Referencing foreign key in Django Python

How to assign a product in ProductInStore to an instance of a Product already in store? Basically i have a scrapper and im looping through all the products and i need to first create the Product instance, and then A ProductInStore instance which is connected to Product via foreignKey. And when i try to put in ProductInStore(product=id) thats how i wanted to reference that Product, i get an error ValueError: Cannot assign "11393": "ProductInStore.product" must be a "Product" instance.
Do you have any idea how to reference it?
class Product(models.Model):
name = models.CharField(max_length=200)
slug = models.SlugField(max_length=200, unique=True, null=False, editable=False)
created_at = models.DateTimeField(editable=False, default=timezone.now)
updated_at = models.DateTimeField(default=timezone.now)
product_category = models.ManyToManyField(EcommerceProductCategory)
description = RichTextField(max_length=2000, null=True, blank=True)
product_producer = models.ForeignKey('ProductProducer', on_delete=models.CASCADE)
creator = models.ForeignKey('users.CustomUser', on_delete=models.CASCADE, null=True, blank=True, related_name='product_creator')
points_from_reviews = models.DecimalField(max_digits=6, decimal_places=2, default=0, help_text='Średnia ocena produktu')
unique_id = models.CharField(max_length=256, unique=True)
type_of_unique_id = models.CharField(max_length=64)
class ProductInStore(models.Model):
product = models.ForeignKey('Product', on_delete=models.CASCADE)
store = models.ForeignKey('Store', on_delete=models.CASCADE)
price = models.DecimalField(max_digits=6, decimal_places=2, default=0, help_text='Cena w sklepie')
currency = models.CharField(max_length=4)
url = models.CharField(max_length=200)
created_at = models.DateTimeField(editable=False, default=timezone.now)
updated_at = models.DateTimeField(default=timezone.now)
# ADD TO DATABASE
try:
db_product = Product.objects.create(name=name, slug=slug, product_producer_id=3, unique_id=id,
description=description)
db_product.product_category.set(parsed_categories)
except:
print('product already in database')
ProductInStore.objects.create(product=,store=1,price=price,currency='PLN',url=url)
You can simply do this:
ProductInStore.objects.create(product_id=id, store=1, price=price, currency='PLN', url=url)
You don't need to pass the object if you have the ID of it, simply append _id to the field name and you can reference the foreign key that way.

Django multiple foreign key to a same table

I need to log the transaction of the item movement in a warehouse. I've 3 tables as shown in the below image. However Django response error:
ERRORS:
chemstore.ItemTransaction: (models.E007) Field 'outbin' has column name 'bin_code_id' that is used by another field.
which is complaining of multiple uses of the same foreign key. Is my table design problem? or is it not allowed under Django? How can I achieve this under Django? thankyou
DB design
[Models]
class BinLocation(models.Model):
bin_code = models.CharField(max_length=10, unique=True)
desc = models.CharField(max_length=50)
def __str__(self):
return f"{self.bin_code}"
class Meta:
indexes = [models.Index(fields=['bin_code'])]
class ItemMaster(models.Model):
item_code = models.CharField(max_length=20, unique=True)
desc = models.CharField(max_length=50)
long_desc = models.CharField(max_length=150, blank=True)
helper_qty = models.DecimalField(max_digits=10, decimal_places=4)
unit = models.CharField(max_length=10, blank=False)
def __str__(self):
return f"{self.item_code}"
class Meta:
verbose_name = "Item"
verbose_name_plural = "Items"
indexes = [models.Index(fields=['item_code'])]
class ItemTransaction(models.Model):
trace_code = models.CharField(max_length=20, unique=False)
item_code = models.ForeignKey(
ItemMaster, related_name='trans', on_delete=models.CASCADE, null=False)
datetime = models.DateTimeField(auto_now=False, auto_now_add=False)
qty = models.DecimalField(max_digits=10, decimal_places=4)
unit = models.CharField(max_length=10, blank=False)
action = models.CharField(
max_length=1, choices=ACTION, blank=False, null=False)
in_bin = models.ForeignKey(
BinLocation, related_name='in_logs', db_column='bin_code_id', on_delete=models.CASCADE, null=False)
out_bin = models.ForeignKey(
BinLocation, related_name='out_logs', db_column='bin_code_id', on_delete=models.CASCADE, null=False)
remarks = models.TextField(blank=True)
def __str__(self):
return f"{self.trace_code} {self.datetime} {self.item_code} {dict(ACTION)[self.action]} {self.qty} {self.unit} {self.in_bin} {self.out_bin}"
you have same db_column in two fields so change it
in_bin = models.ForeignKey(
BinLocation, related_name='in_logs', db_column='bin_code_id', on_delete=models.CASCADE, null=False)
out_bin = models.ForeignKey(
BinLocation, related_name='out_logs', db_column='other_bin_code', on_delete=models.CASCADE, null=False) /*change db_column whatever you want but it should be unique*/
If are linked to the same model name, You should use different related_name for each foreign_key filed . here is the exemple :
address1 = models.ForeignKey(Address, verbose_name=_("Address1"),related_name="Address1", null=True, blank=True,on_delete=models.SET_NULL)
address2 = models.ForeignKey(Address, verbose_name=_("Address2"),related_name="Address2", null=True, blank=True,on_delete=models.SET_NULL)
thank you for everyone helped. According to Aleksei and Tabaane, it is my DB design issue (broken the RDBMS rule) rather than Django issue. I searched online and find something similar: ONE-TO-MANY DB design pattern
In my case, I should store in bin and out bin as separated transaction instead of both in and out in a single transaction. This is my solution. thankyou.
p.s. alternative solution: I keep in bin and out bin as single transaction, but I don't use foreign key for bins, query both in bin and out bin for the bin selection by client application.

Python django Need return name instead of id foreginkey

class Product(models.Model):
name = models.CharField(max_length=300, default='default name')
description = models.TextField(max_length=800, blank=True, null=True)
link = models.TextField(default='0')
type = models.ForeignKey(ProductType, on_delete=models.CASCADE, null=True, blank=True)
category = models.ForeignKey(ProductCategory, on_delete=models.CASCADE, null=True, blank=True)
keyword = models.OneToOneField(KeyWords, on_delete=models.CASCADE, null=True, blank=True)
model don't return data from ForeignKey
p = Product.objects.get(...)
p.type.name
p.category.name
I think you need to define a __str__ method in your ProductCategory model. This way you will have a descriptive name for each entry into that table. Without it, your entry is best described by the id field.

Categories

Resources