First, I know there are a lot of answers regarding this error, but I can't understand why this is erroring out in my case. I am learning Django and any help would be highly appreciated.
I have a Ticket model with ForeignKey reference to Category, Type & GHDUser as below
models.py
`
# from accounts/models.py
class GHDUser(AbstractBaseUser, PermissionsMixin):
emp_id = models.IntegerField(primary_key=True)
email = models.EmailField(_('email address'),unique=True)
username = models.CharField(max_length=150, unique=True)
# from ticket/models.py
class Category(models.Model):
name = models.CharField(max_length=100)
class Meta:
verbose_name = 'Category'
verbose_name_plural = 'Categories'
def __str__(self):
return self.name
class Type(models.Model):
category = models.ForeignKey(Category, on_delete=models.CASCADE)
name = models.CharField(max_length=100)
class Meta:
verbose_name = 'Type'
verbose_name_plural = 'Types'
def __str__(self):
return self.name
class Ticket(models.Model):
status_options = (
('open', 'Open'),
('pending', 'Pending'),
('closed', 'Closed')
)
priority_options = (
('high','High'),
('medium','Medium'),
('low','Low')
)
ticket_no = models.CharField(max_length=10, blank=True)
title = models.CharField(max_length=100)
description = models.TextField(max_length=1000)
category = models.ForeignKey(Category, on_delete=models.PROTECT, default=1)
type = models.ForeignKey(Type, on_delete=models.PROTECT, default=1)
file = models.FileField(upload_to=user_directory_path, blank=True, default='files/Default_Avatar.png')
raised_by_user = models.ForeignKey(GHDUser, on_delete=models.CASCADE, related_name='raised_ticket')
`
Now, I am able to create an instance for Ticket model from Admin Panel, but when I try to do the same via shell / using data from front end, I am getting the below error.
django.db.utils.IntegrityError: FOREIGN KEY constraint failed
Can you please help me understand what I am doing wrong ?
Related
models.py
class FarmerAdvisory(BaseModel):
id = models.AutoField(db_column='id', primary_key=True)
title = models.CharField(db_column='title', max_length=200, null=True, blank=True)
description = models.CharField(db_column='description', max_length=750, null=True, blank=True)
farmer_id = models.ForeignKey(Farmer, on_delete=models.CASCADE, null=True, db_column='farmer_id')
class Meta:
verbose_name = 'Farmer Advisory'
verbose_name_plural = 'Farmer Advisories'
managed = True
db_table = 'farmer_advisory'
class ReplyFarmerAdvisory(BaseModel):
reply = models.CharField(db_column='reply', max_length=750, null=True, blank=True)
label = models.CharField(db_column='label', max_length=100, null=True, blank=True)
farmer_advisory_id = models.ForeignKey(FarmerAdvisory, on_delete=models.CASCADE, db_column='farmer_advisory_id')
objects = models.Manager()
class Meta:
verbose_name = 'Reply Farmer Advisory'
verbose_name_plural = 'Reply Farmer Advisories'
managed = True
db_table = 'reply_farmer_advisory'
class AdvisoryMedia(models.Model):
id = models.AutoField(db_column='id', primary_key=True)
farmer_advisory_id = models.ForeignKey(FarmerAdvisory, on_delete=models.CASCADE,
db_column='farmer_advisory_id',
null=True, blank=True)
reply_farmer_advisory_id = models.ForeignKey(ReplyFarmerAdvisory, on_delete=models.CASCADE,
db_column='reply_farmer_advisory_id', null=True, blank=True)
farmer_media_file = models.CharField(db_column='farmer_media_file', max_length=50, null=True, blank=True)
is_active = models.BooleanField(db_column='is_active', null=False, default=True)
reply_media_file = models.FileField(upload_to=content_file_name, null=True, blank=True,
db_column='reply_media_file')
class Meta:
verbose_name = 'Advisory Media'
verbose_name_plural = 'Advisories Media'
managed = True
db_table = 'advisory_media'
admin.py
class AdvisoryMediaInline(NestedStackedInline):
model = AdvisoryMedia
extra = 0
class ReplyFarmerAdvisoryInline(NestedStackedInline):
model = ReplyFarmerAdvisory
extra = 1
inlines = [AdvisoryMediaInline]
class FarmerAdvisoryAdmin(NestedModelAdmin):
inlines = [ReplyFarmerAdvisoryInline]
I want to show the fields with respect to the farmer advisory. But when i am adding fk_name = 'farmer_advisory_id' inside AdvisoryMediaInline, i am getting error stating
ValueError: fk_name 'farmer_advisory_id' is not a ForeignKey to
'farmer.ReplyFarmerAdvisory'.
But i want to show the farmer advisory related fields which is not coming by itself.
I think what is happening is the model is looking for values with respect to the to foreign key reply advisory media instead of farmer advisory media.
Please let me know if my question is understandable, if yes please guide me through it.
Hello I was wondering could anyone help me with an issue I've ran into while working on a Django project. I've tried a few different things but cant seem to get it working a screenshot of the error is attached.
[![enter image description here][1]][1]
error
[1]: https://i.stack.imgur.com/LKTPu.png
import uuid
from django.db import models
from django.urls import reverse
class Category(models.Model):
id = models.UUIDField(
primary_key=True,
default=uuid.uuid4,
editable=False)
name = models.CharField(max_length=250, unique=True)
description = models.TextField(blank=True)
image = models.ImageField(upload_to='category', blank=True)
class Meta:
ordering = ('name',)
verbose_name = 'category'
verbose_name_plural = 'categories'
def get_absolute_url(self):
return reverse('phoneshop:products_by_category', args=[self.id])
def __str__(self):
return self.name
class Product(models.Model):
id = models.UUIDField(
primary_key=True,
default=uuid.uuid4,
editable=False)
name = models.CharField(max_length=250, unique=True)
description = models.TextField(blank=True)
category = models.ForeignKey(Category, on_delete=models.CASCADE)
price = models.DecimalField(max_digits=10, decimal_places=2)
image = models.ImageField(upload_to='product', blank=True)
stock = models.IntegerField()
available = models.BooleanField(default=True)
created = models.DateTimeField(auto_now_add=True, blank=True, null=True)
updated = models.DateTimeField(auto_now_add=True, blank=True, null=True)
class Meta:
ordering = ('name',)
verbose_name = 'product'
verbose_name_plural = 'products'
def get_absolute_url(self):
return reverse('phoneshop:prod_detail', args=[self.Category.id, self.id])
def __str__(self):
return self.name
After adding one of the model fields to select an option from a list, I get a field error. What could possibly be the cause and the solution to this
ERROR:
File "/home/chrisdev/code/work/cw-full/lib/python3.8/site-packages/django/db/models/sql/query.py", line 1481, in names_to_path
raise FieldError("Cannot resolve keyword '%s' into field. "
django.core.exceptions.FieldError: Cannot resolve keyword 'status' into field. Choices are: description, id, image, name, slug
MODEL:
from django.db import models
from django.contrib.auth.models import User
# News Model
class News(models.Model):
DRAFT = 'DRT'
PUBLISHED = 'PUB'
article_publication_choices = [
(DRAFT, 'Draft'),
(PUBLISHED, 'Published'),
]
title = models.CharField('News Title', max_length=200, unique=True, help_text='News Heading')
slug = models.SlugField(max_length=200, unique=True)
author = models.ForeignKey(User, on_delete= models.SET_NULL, related_name='news', null=True)
updated_on = models.DateTimeField(auto_now= True)
news_summary = models.CharField('News Summary', max_length=200)
content = models.TextField('News Content')
created_on = models.DateTimeField(auto_now_add=True)
article_publication = models.CharField(max_length=2,
choices=article_publication_choices,
default=PUBLISHED,
)
class Meta:
verbose_name = 'News Updates'
verbose_name_plural = verbose_name
ordering = ['-created_on']
def __str__(self):
return self.title
I found the solution to this, by adding related_name='+', at the field that uses a relationship from other models
I want to convert the following query of SQL into Django Query-set:-
select sum(amount) from accounts_order where status='Pending' and
customer_id=1;
here is my models.py file
from django.db import models
Create your models here.
class Customer(models.Model):
"""All Customers details goes here"""
name = models.CharField(max_length=255, null=False)
email = models.EmailField(null=False)
phone_number = models.CharField(max_length=255, null=False)
date_created = models.DateTimeField(auto_now_add=True)
class Meta:
"""Meta definition for Customer."""
verbose_name = 'Customer'
verbose_name_plural = 'Customers'
def __str__(self):
"""Unicode representation of Customer."""
return self.name
class Order(models.Model):
"""All order details goes here.It has OneToMany relationship with Customer"""
STATUS = (
('Pending', 'Pending'),
('Done', 'Done'),
)
customer = models.ForeignKey(
Customer, null=True, on_delete=models.SET_NULL)
bill_name = models.CharField(max_length=255, null=False)
status = models.CharField(max_length=255, choices=STATUS, null=False)
amount = models.FloatField(max_length=255, null=False)
date_created = models.DateTimeField(auto_now_add=True)
class Meta:
"""Meta definition for Order."""
verbose_name = 'Order'
verbose_name_plural = 'Orders'
def __str__(self):
"""Unicode representation of Order."""
return self.bill_name
You can use a .aggregate(…) [Django-doc] here:
from django.db.models import Sum
Order.objects.filter(
status='Pending', customer_id=1
).aggregate(total_amount=Sum('amount'))['total_amount']
I have this situation:
Model Handling
class Handling(models.Model):
STATUS = (
('Active', 'Active'),
('Archived', 'Archived'),
)
entdate = models.DateTimeField(auto_now_add=True, null=True)
extdate = models.DateTimeField(auto_now_add=True, null=True)
kpallet = models.ForeignKey(Pallet, related_name='kpallet', null=True, on_delete= models.PROTECT)
kitem = models.ForeignKey(Item,related_name='kitems', null=True, on_delete= models.PROTECT, limit_choices_to={'kstatus': 'Active'})
quantity = models.SmallIntegerField(null=True)
kstatus = models.CharField(max_length=20, null=True, choices=STATUS)
def __str__(self):
return str(self.kpallet)
Model Item:
class Item(models.Model):
STATUS = (
('Active', 'Active'),
('Disabled', 'Disabled'),
('Archived', 'Archived'),
)
id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
name = models.CharField(max_length=50, null=True)
description = models.CharField(max_length=200, null=True)
kdimension = models.ForeignKey(Dimension, null=True, on_delete= models.PROTECT)
kclient = models.ForeignKey(Client, null=True, on_delete= models.PROTECT)
kstatus = models.CharField(max_length=20, null=True, choices=STATUS)
def __str__(self):
return self.name
Serializer:
class HandlingSerializer(serializers.ModelSerializer):
class Meta:
model = Handling
fields = '__all__'
Api:
#api_view(['POST'])
#permission_classes((permissions.AllowAny,))
def handlingCreate(request):
serializer = HandlingSerializer(data=request.data)
if serializer.is_valid():
serializer.save()
else:
print(serializer.errors);
return Response("Error Handling not created")
return Response("Handling Created")
I get this error and i don't understand how to move on:
{'kitem': [ErrorDetail(string='Invalid pk "958c2fd2-bbb6-42d6-8bfe-fbe035e9ceb5" - object does not exist.', code='does_not_exist')]}
I've checked the pk and the object exists so I don't understand where the issue could be.
Thanks for your help in advance.
Fixed thanks to Blackdoor for the input.
This is the correct serializer:
class HandlingSerializer(serializers.ModelSerializer):
kitem = serializers.PrimaryKeyRelatedField(queryset=Item.objects.all(), pk_field=serializers.UUIDField(format='hex_verbose'))
class Meta:
model = Handling
fields = '__all__'
use pk_field=UUIDField for PrimaryKeyRelatedField
class HandlingSerializer(serializers.ModelSerializer):
kitem = serializers.PrimaryKeyRelatedField(queryset=Item.objects.all(), pk_field=UUIDField(format='hex'))
class Meta:
model = Handling
fields = '__all__'