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
Related
There was no manager in the posts I created before. When I add the manager, I want the default value or I am asked to enter it manually. When I enter 'None' I get an error like this;
django.db.utils.IntegrityError: NOT NULL constraint failed:
new__Core_post.manager_id
I cannot export PostManager as the default value. Is there another way or another solution to give?
class User(models.Model):
#...
posts = models.ManyToManyField('Post', blank=True)
class Post(models.Model):
owner = models.ForeignKey(User, on_delete=models.CASCADE)
#...
manager = models.ForeignKey('PostManager', on_delete=models.CASCADE)
class PostManager(models.Model):
#...
Sorry for my bad english.
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'm having problems with the concept of relationship in django models.
Let's see my example:
I have this table/class into models.py:
class PacketEventsInformation(models.Model):
ID_IP_Source = models.<Relationship>(Ips, on_delete=models.CASCADE)
ID_IP_Dest = models.<Relationship>(Ips, on_delete=models.CASCADE)
ID_Source_Port = models.<Relationship>(Ports, on_delete=models.CASCADE)
ID_Dest_Port = models.<Relationship>(Ports, on_delete=models.CASCADE)
Protocol = models.CharField(max_length=20)
ID_Source_MAC = models.<Relationship>(Macs, on_delete=models.CASCADE)
ID_Dest_MAC = models.<Relationship>(Macs, on_delete=models.CASCADE)
RAW_Info = models.TextField()
TAG = models.ForeignKey(Tags, on_delete=models.CASCADE)
def __str__(self):
return '%s' % self.id
At this point, I defined the relationship between all my ID fields and ID fields of another tables/classes (Pkey) like ForeignKey.
Well, If I execute migrate into my terminal, I get this:
./manage.py migrate
app.PacketEventsInformation.ID_Dest_MAC: (fields.E304) Reverse accessor for 'PacketEventsInformation.ID_Dest_MAC' clashes with reverse accessor for 'PacketEventsInformation.ID_Source_MAC'.
......
I understand the definition of ManyToMany, OneToOne and OnetoMany (Foreign Key), but I have no idea why can't do it this. Maybe the answer could be create intermediate tables with that Fkeys or put OneToOne relation between that ids....
Thanks for your answers =)
PD:
ID_IP_Source/Dest can be the same
ID_Source/Dest_Port can be the same
ID_Source/Dest_MAC can be the same
In django when you have multiple foreign keys pointing at the same model, you need to use related_name to distinguish them:
ID_IP_Source = models.<Relationship>(Ips, on_delete=models.CASCADE, related_name="id_ip_source")
ID_IP_Dest = models.<Relationship>(Ips, on_delete=models.CASCADE, related_name="id_ip_dest")
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"
)
I'm trying to create a unique constraint on my TranslationRequest model listed below. TranslationRequest has a foreign key relationship with a MachineTranslator model, which exists in another Django application. When I try to run syncdb, I get the error: Error: One or more models did not validate:
wt_articles.translationrequest: "unique_together" refers to translator, a field that doesn't exist. Check your syntax.
When I remove translator from the unique_constraint specification, syncdb runs correctly. Note: I'm using Sqlite3 as my back-end database.
Here are the definitions of TranslationRequest and SourceArticle.
from wt_translation.models import MachineTranslator
class TranslationRequest(models.Model):
article = models.ForeignKey(SourceArticle)
target_language = models.ForeignKey(Language, db_index=True)
date = models.DateTimeField(_('Request Date'))
translator = models.ForeignKey(MachineTranslator),
status = models.CharField(_('Request Status'),
max_length=32,
choices=TRANSLATION_STATUSES)
class Meta:
unique_together = ("article", "target_language", "translator")
class SourceArticle(models.Model):
title = models.CharField(_('Title'), max_length=255)
language = models.ForeignKey(Language, db_index=True)
timestamp = models.DateTimeField(_('Import Date'), default=datetime.now())
doc_id = models.CharField(_('Document ID'), max_length=512)
source_text = models.TextField(_('Source Text'))
sentences_processed = models.BooleanField(_('Sentences Processed'))
Here is the definition of MachineTranslator, in a different (but referenced Django application).
class MachineTranslator(models.Model):
shortname = models.CharField(_('Name'), max_length=50)
supported_languages = models.ManyToManyField(LanguagePair)
description = models.TextField(_('Description'))
type = models.CharField(_('Type'), max_length=32, choices=TRANSLATOR_TYPES, default='Serverland'),
timestamp = models.DateTimeField(_('Refresh Date'), default=datetime.now())
is_alive = models.BooleanField()
Not all of the dependencies have been included in this code sample. Thanks for your help!
i dont' know if it is a typo but i see s "," comma at the end of the line where you declare your translator = models.ForeignKey(MachineTranslator)
This is why maybe the attribute is ot seens