I have News and Page models, and News has two fields referencing to Page:
chapter = models.ForeignKey('pages.Page',
verbose_name='Main chapter',
limit_choices_to={'type__in':['news','speech']},
related_name='news'
)
add_chapters = models.ManyToManyField('pages.Page', blank=True, null=True,
verbose_name='Show also on',
limit_choices_to={'allow_add_news':True},
related_name="added_news"
)
The problem is that if I'm trying to save News from django admin (with some pages selected for add_chapters) - I get the
IntegrityError (1452, 'Cannot add or update a child row: a foreign key
constraint fails
(site.news_news_add_chapters,
CONSTRAINT news_id_refs_id_479506ad
FOREIGN KEY (news_id) REFERENCES
news_news (id))')
What's wrong?
This works OK for me with Django 1.2 and sqlite and mysql. I think your db scheme is wrong. Try it on a fresh db and check if it is working.
(Check your code - keep in mind that type is a python built_in. Did you use type instead of self.type somewhere?).
The code I used:
# models.py
class Page(models.Model):
name = models.CharField(max_length=128)
type = models.CharField(max_length=128, default="news")
allow_add_news = models.BooleanField(default=True)
class News(models.Model):
name = models.CharField(max_length=128)
chapter = models.ForeignKey(Page,
verbose_name='Main chapter',
limit_choices_to={'type__in':['news','speech']},
related_name='news'
)
add_chapters = models.ManyToManyField(Page, blank=True, null=True,
verbose_name='Show also on',
limit_choices_to={'allow_add_news':True},
related_name="added_news"
)
Related
So I Am Making A Shop Website I wanted to ask how do we add tables as a field? Do we use foreign key or something in Django I am using SQLite btw
https://i.stack.imgur.com/W1Y5H.png
I think you want to use model fields as table fields. Basically, you require ORM(Object-relational mapping). I am adding a basic model snippet below with a foreign key added.
class Collection(models.Model):
title = models.CharField(max_length=255)
# This for foreign key .The plus sign means that a reverse relation won't be created!
featured_product = models.ForeignKey('Product',on_delete=models.SET_NULL,null=True,related_name='+')
class Product(models.Model):
sku = models.CharField(max_length=10,primary_key=True)
title = models.CharField(max_length=255)
slug = models.SlugField(default='-')
description = models.TextField()
unit_price = models.DecimalField(max_digits=6,decimal_places=2)
inventory = models.IntegerField()
last_update = models.DateTimeField(auto_now=True)
collection = models.ForeignKey(Collection,on_delete=models.CASCADE)
I have a many-to-many relation on field tag and a foreign key field appName, I want to select only the tags that are related to the specific appNames.
Now, when the dropdown for selection is opened it displays all the many-to-many fields irrespective of its related apps.
class AppName(models.Model):
appId = models.AutoField(primary_key=True)
appName = models.CharField(max_length=200)
appVersion = models.CharField(max_length=100,blank=True)
appVersionName = models.CharField(max_length=100,blank=True)
appPackageName = models.CharField(max_length=300)
class Tag(models.Model):
tagId = models.AutoField(primary_key=True)
tag = models.CharField(max_length=300)
tagDes = models.TextField()
tagAddedDate = models.DateTimeField(default=timezone.now)
appName = models.ForeignKey(AppName,on_delete=models.CASCADE, null=True, blank=True)
class Company(models.Model):
CId = models.AutoField(primary_key=True)
appName = models.ForeignKey(AppName,on_delete=models.CASCADE, null=True, blank=True)
tag = models.ManyToManyField(Tag,blank=True)
The expected output is a list of tags with respect to the appName selected.
The question is not entirely clear for me, but it seems that you want to have 'chained' dropdown lists. As far as i know it is not doeable without some requests.
I followed tutorial from:
https://simpleisbetterthancomplex.com/tutorial/2018/01/29/how-to-implement-dependent-or-chained-dropdown-list-with-django.html
and it worked perfectly in my case. So basically you need some ajax requests.
I have a webservice setup with Django backend and I am trying to delete entries for my Field objects. Each Field is assigned to a User and there are a number of Assessments done in the Field. The Assessments are linked to the Fields via a foreign key. Upon deletion of the Field object I want to also delete all the Assessments for that Field, but keep the User.
I played around with the on_deletion parameter and if I set it to CASCADE the Django admin page shows me all the associated Assessment objects if I try to delete the Field object. However, I am still getting the following error:
IntegrityError at /admin/dfto/field/ update or delete on table "field"
violates foreign key constraint "assessment_field_uuid_fkey" on table
"assessment" DETAIL: Key
(uuid)=(f3a52c10-33be-42f9-995d-482025cea17b) is still referenced from
table "assessment".
These are my models for Reference:
class Assessment(models.Model):
uuid = models.TextField(primary_key=True)
longitude = models.FloatField(blank=True, null=True)
latitude = models.FloatField(blank=True, null=True)
field_uuid = models.ForeignKey('Field', models.CASCADE, db_column='field_uuid',blank=True, null=True, related_name='assessments')
class Meta:
db_table = 'assessment'
class Field(models.Model):
uuid = models.TextField(primary_key=True)
name = models.CharField(max_length=50, blank=True, null=True)
country = models.CharField(max_length=50, blank=True, null=True)
user_email = models.ForeignKey('User', models.DO_NOTHING, db_column='user_email')
crop_uuid = models.ForeignKey(Crop, models.CASCADE, db_column='crop_uuid')
class Meta:
db_table = 'field'
Can someone explain to me why I am getting this error and/or provide a fix for me?
I think it's because field_uuid have argument 'models.CASCADE' so when you are deleting it, django also tries to delete any refences to this particular key, don't know how to fix it tho.
I am getting the following error after trying to add a foreignkey from CrackingJob.hash_mode_numeric to HashMappings.
Initially i was trying to set the FK directly to HashMappings.hash_mode_numeric without the unique constraint and it rightly gave the error, but after adding unique=True i still get the error. Even when i try to just use the PK (auto generated unique id) as FK, like in the code below.
django.db.utils.ProgrammingError: there is no unique constraint
matching given keys for referenced table "appname_hashmappings"
Relevant code:
class HashMappings(models.Model):
hash_name = models.CharField(max_length=255, unique=True)
hash_mode_numeric = models.IntegerField(unique=True)
example_hash = models.TextField(max_length=2500)
supported = models.BooleanField(default=0)
class Meta:
ordering = ['hash_name']
def __str__(self):
return f'{self.hash_name}'
class CrackingJob(models.Model):
user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.SET_NULL)
description = models.CharField(max_length=255)
hash_mode_numeric = models.ForeignKey(HashMappings, on_delete=models.CASCADE)
try to clear data in hashmappings table and then run migrate command -> python manage.py migrate
I am trying to override the default django admin change url.
In my table i have composite primary key.
class ABC(models.Model):
code = models.ForeignKey('PQR', models.DO_NOTHING, db_column='code', primary_key=True)
language = models.ForeignKey(Languages, models.DO_NOTHING, db_column='language')
me_name = models.TextField()
common_name = models.TextField(blank=True, null=True)
abbreviation = models.TextField(blank=True, null=True)
class Meta:
managed = False
db_table = 'abc'
unique_together = (('code', 'language'), ('language', 'me_name'),)
Now my admin url in django admin for each object is /admin/home/abc/{{code}}/change/.
But i have repeated codes in objects because primary key is composite of ('code', 'language'). So for objects which have repeated code are throwing
Error
MultipleObjectsReturned at /admin/home/abc/X00124/change/
get() returned more than one ABC -- it returned 2!
here X00124 this code associated with more than one object.
What i want here that override the modeladmins get_urls() method and construct the url /admin/home/abc/{{code}}/{{language}}/change/.
I tried but no success. Help will be appreciated.
I made a virtual key, that represents compound key as a single value, that allows to use Django admin without code changes -
https://viewflow.medium.com/the-django-compositeforeignkey-field-get-access-to-a-legacy-database-without-altering-db-tables-74abc9868026