When I update/delete some content through views.py file i.e via the website, everything works fine but when I try to update some data through admin panel i get this error:
IntegrityError at /admin/library/student/
(1452, 'Cannot add or update a child row: a foreign key constraint fails (kt2.django_admin_log, CONSTRAINT django_admin_log_user_id_52fdd58701c5f563_fk_auth_user_id FOREIGN KEY (user_id) REFERENCES auth_user (id))')
where kt2 is the name of my database.
Please help and also let me know if you need the code.
models.py
# Create your models here.
from django.db import models
from django.contrib.auth.models import AbstractUser
# Create your models here.
class Student(AbstractUser):
roll_number = models.CharField(max_length=30,unique=True)
student_name = models.CharField(max_length=200)
branch = models.CharField(max_length=20)
sem = models.IntegerField()
pic = models.ImageField(null=True,blank=True)
due_fine = models.IntegerField(default=0)
USERNAME_FIELD='roll_number'
REQUIRED_FIELDS=['username','email']
def __str__(self):
return self.student_name
class Author(models.Model):
author_name = models.CharField(max_length=200,primary_key=True)
def __str__(self):
return self.author_name
class Quantity(models.Model):
q_id=models.AutoField(primary_key=True)
book_name=models.CharField(max_length=200)
list_of_authors=models.ManyToManyField(Author)
qty = models.IntegerField(default=1)
class Meta:
verbose_name_plural = 'Quantity'
# unique_together=(('book_name','list_of_authors'),)
def __str__(self):
return self.book_name
class LastFiveIssues(models.Model):
lfi_id=models.AutoField(primary_key=True)
one_st=models.CharField(max_length=30,blank=True,null=True)
two_st=models.CharField(max_length=30,blank=True,null=True)
three_st=models.CharField(max_length=30,blank=True,null=True)
four_st=models.CharField(max_length=30,blank=True,null=True)
five_st=models.CharField(max_length=30,blank=True,null=True)
issue_one_date=models.DateField(blank=True,null=True)
issue_two_date=models.DateField(blank=True,null=True)
issue_three_date=models.DateField(blank=True,null=True)
issue_four_date=models.DateField(blank=True,null=True)
issue_five_date=models.DateField(blank=True,null=True)
return_one_date=models.DateField(blank=True,null=True)
return_two_date=models.DateField(blank=True,null=True)
return_three_date=models.DateField(blank=True,null=True)
return_four_date=models.DateField(blank=True,null=True)
return_five_date=models.DateField(blank=True,null=True)
class Meta:
verbose_name_plural='last five issues'
class Publisher(models.Model):
publisher_name = models.CharField(max_length=200,primary_key=True)
def __str__(self):
return self.publisher_name
class Book(models.Model):
last_five_issues=models.OneToOneField(LastFiveIssues)
publisher_book=models.ForeignKey(Publisher)
authors = models.ForeignKey(Quantity)
student = models.ForeignKey(Student)
book_id = models.CharField(primary_key=True,max_length=30)
is_issued = models.BooleanField(default=False)
dep_book = models.CharField(max_length=20)
book_name = models.CharField(max_length=200)
date_of_issue = models.DateField(default = '1900-1-1')
return_date = models.DateField(default='1900-1-1')
book_added_on = models.DateField(default='1900-1-1')
placed_at_shelf=models.CharField(max_length=200,blank=True,null=True)
edition_of_book = models.IntegerField()
rare_book = models.BooleanField(default=False)
claim_one=models.CharField(max_length=30,blank=True,null=True)
claim_two=models.CharField(max_length=30,blank=True,null=True)
claim_three=models.CharField(max_length=30,blank=True,null=True)
def __str__(self):
return self.book_name
Related
This is my models.py:
class UnitOfMeasurement(models.Model):
active = models.BooleanField(default=True)
name = models.CharField(max_length=255)
measurement_type = models.CharField(max_length=255)
def __str__(self):
return self.name
class Category(models.Model):
name = models.CharField(max_length=250)
abbreviation=models.CharField(max_length=10)
active = models.BooleanField(default=True)
description=models.CharField(max_length=500,blank=True, null=True)
def __str__(self):
return self.name
class Product(models.Model):
active = models.BooleanField(default=True)
bar_code = models.CharField(max_length=50, blank = True, null = True)
name = models.CharField(max_length=250)
category = models.ForeignKey(
Category, on_delete=models.CASCADE, related_name='product')
brand = models.CharField(max_length=250)
model = models.CharField(max_length=250)
tag = models.CharField(max_length=250, null=True)
remarks = models.TextField(null=True)
gstcode = models.ForeignKey(
GSTCode, on_delete=models.CASCADE, related_name='product', null=True)
unit_of_measurement = models.ForeignKey(
UnitOfMeasurement, on_delete=models.DO_NOTHING, related_name='category')
# picture
objects=ProductManager()
# select the product where active=true & quantity<0
def __str__(self):
return self.name
So how do I need to code my serializers and views in order to get the data that returns name, category, brand, model, tag from Product Model and name from Category Model and also name and measurement_type from UnitOfMeasurement Model?
You can select fields from model in serializer as below example code for UnitOfMeasurement and use this serializer for get(retrieve) request.
class UnitOfMeasurementSerializer(serializers.ModelSerializer):
class Meta:
model = UnitOfMeasurement
fields = ["name", "measurement_type"]
Same thing you can do for rest of models.
Views depends on your use case.
Good day everyone! I'am new to django and i want to learn a lot in this excellent framework. I want to learn in django-import-export application and I have trouble in exporting data from mysql table. Django-import-export application export foreign key id rather than the foreign key I specified in to_field.
Below is my model
from django.db import models
class Rank(models.Model):
RankCode = models.CharField(max_length=20, null=False, blank=False, unique=True)
RankDesc = models.CharField(max_length=60, null=False, blank=False)
OrderNo = models.IntegerField(null=True, blank=True)
def __str__(self):
return "%s" % self.RankCode
class Status(models.Model):
StatusCode = models.CharField(max_length=60, null=False, blank=False, unique=True)
class Meta:
verbose_name_plural = 'Status'
def __str__(self):
return "%s" % self.StatusCode
class Student(models.Model):
Rank = models.ForeignKey(Rank, to_field='RankCode', on_delete=models.CASCADE)
Name = models.CharField(max_length=200, null=False, blank=False, unique=True)
Status = models.ForeignKey(Status, to_field='StatusCode', on_delete=models.CASCADE)
Age = models.IntegerField(null=True, blank=True)
def __str__(self):
return "%s" % self.Rank
If I export Student model to excel, I want the output to be the value of specified foreign key in to_field and not the id.
Thanks in advance to those who can contribute.
I'm trying to associate Comment with User models, but somehow the field is not being created in the database. When I try to access the page, the following error is shown:
(1054, "Unknown column 'user_comments.user_id' in 'field list'")
These are in the models.py:
class User(models.Model):
username = models.CharField(max_length=128)
password = models.CharField(max_length=128)
first_name = models.CharField(max_length=128)
last_name = models.CharField(max_length=128)
email = models.CharField(max_length=128)
date_joined = models.DateField(auto_now_add=True)
class Meta:
db_table = 'auth_user'
ordering = ('date_joined',)
class Comment(models.Model):
user = models.ForeignKey('auth.User', related_name='comments', on_delete=models.CASCADE)
content = models.CharField(max_length=256)
date_created = models.DateField(auto_now_add=True)
class Meta:
db_table = 'user_comments'
ordering = ('date_created',)
def __str__(self):
return self.content
def save(self, *args, **kwargs):
content = self.content
super(Comment, self).save(*args, **kwargs)
If I name the user variable to user_id, an error saying user_id_id wasn't found will show upon creating a new Comment in the admin panel.
** Update **
I dropped the whole database and I removed the db_table options, and thus user_id has been created. But now, upon creation of a new Comment, the following:
IntegrityError at /admin/api/comment/add/
(1452, 'Cannot add or update a child row: a foreign key constraint fails (`softwarestore`.`api_comment`, CONSTRAINT `api_comment_user_id_14315666_fk_api_user_id` FOREIGN KEY (`user_id`) REFERENCES `api_user` (`id`))')
Have you tried simply replacing following:
user = models.ForeignKey('auth.User', related_name='comments', on_delete=models.CASCADE)
with
user = models.ForeignKey(User, related_name='comments', on_delete=models.CASCADE)
and run makemigrations?
I'm using the the built in django admin site to save instances of a model that has a ManyToMany field. If I save, not update, a model in the admin site without setting a value for the ManyToMany field it saves fine. I can also come back and set the ManyToMany field after saving the model and that works. However, if I try to save a new instance of my model, Exercise, that has the ManyToMany field, Exercise.muscles, set I get the following error:
(1452, 'Cannot add or update a child row: a foreign key constraint fails
(vitality.projectvitality_exercise_muscles, CONSTRAINT exercise_id_refs_exercise_id_a5d4ddd6 FOREIGN KEY (exercise_id) REFERENCES projectvitality_exercise (exercise_id))')
My mysql tables are set to INNODB.
My models are as follows:
class Muscle(models.Model):
def format(self):
return "name:{0}:".format(self.name)
def __unicode__(self):
return unicode(self.name)
muscle_id = UUIDField(primary_key = True)
name = models.CharField(max_length=30, blank=False, default="")
medical = models.CharField(max_length=150, blank=True, default="")
description = models.TextField(blank=True, default="")
class Exercise(models.Model):
def format(self):
return "name:{0}".format(self.name)
def __unicode__(self):
return unicode(self.name)
ISOLATION_TYPE = "isolation"
COMPOUND_TYPE = "compound"
FULL_BODY_TYPE = "full"
EXERCISE_TYPES = (
(ISOLATION_TYPE, "Isolation"),
(COMPOUND_TYPE, "Compound"),
(FULL_BODY_TYPE, "Full Body")
)
UPPER_BODY_GROUP = "upper"
LOWER_BODY_GROUP = "lower"
GROUP_CHOICES = (
(UPPER_BODY_GROUP, "Upper Body"),
(LOWER_BODY_GROUP, "Lower Body")
)
exercise_id = UUIDField(primary_key=True)
name = models.CharField(max_length=30, default="", blank=False)
description = models.TextField(blank=True, default="")
group = models.CharField(max_length=255,
choices=GROUP_CHOICES,
blank=False,
default=UPPER_BODY_GROUP)
exercise_type = models.CharField(max_length=255,
choices=EXERCISE_TYPES,
blank=False,
default=ISOLATION_TYPE)
muscles = models.ManyToManyField('Muscle', blank=True, null=True)
class Meta:
verbose_name = "Exercise"
verbose_name_plural = "Exercises"
After several days of debugging I found the issue. In my code I use UUIDField, from django-extensions library, as a primary key. When saving a new instance of Exercise model it is able to generate, set and save the primary key. However, when saving a new instance of Exercise that has the ManyToMany field set, UUIDField isn't generated in time. This leads to the Django admin attempting to insert a null/empty primary key, the UUIDField in Exercise model, into the join table which triggers the Foreign Key constraint failure.
I have the following tables. The ComponentBuild table has two columns 'comp_pn' and 'parent_pn' that are both ForeignKeys. Django is complaining Unknown column 'product_parent_pn.product_id_id. What's the correct way to model these relationship?
class Product(models.Model):
name = models.CharField(max_length=80)
def __unicode__(self):
return self.name
class ProductParentPn(models.Model):
part_no = models.CharField(max_length=80)
product_id = models.ForeignKey(Product)
def __unicode__(self):
return self.part_no
class CompMap(models.Model):
component = models.CharField(max_length=50)
part_no = models.CharField(max_length=50)
def __unicode__(self):
return self.part_no
class CompProductMap(models.Model):
comp_id = models.IntegerField()
prod_id = models.IntegerField()
class Meta:
db_table = u'comp_product_map'
class ComponentBuild(models.Model):
comp_sn = models.CharField(max_length=35)
parent_sn = models.CharField(max_length=15)
comp_pn = models.ForeignKey(CompMap)
parent_pn = models.ForeignKey(ProductParentPn)
date = models.DateField(default=datetime.datetime.today())
def __unicode__(self):
return self.comp_sn