Django: Field missing when queried - django

I'm having some trouble querying for my CalculatedAmt field in my database. In fact, according to the error code, the field does not even exist. However, I have included it in my Models.py and it can even be seen in my admin interface on Django.
Here are my codes:
Model.py - I didn't join the tables because I didn't need the join for my queries
class Customer(models.Model):
Customer_Name_P = models.CharField(max_length=30, default="missing")
Customer_TelNo = models.CharField(max_length=8, default="missing")
Postal_Code = models.CharField(max_length=6, default="missing")
def __str__(self):
return "%s" % self.Customer_Name_P
class Transaction(models.Model):
DocRef = models.CharField(max_length=10,default="missing")
DocDate = models.DateField()
AcCrIsMinus1 = models.CharField(max_length=10,default="missing")
AcCurWTaxAmt = models.CharField(max_length=10,default="missing")
HomeWTaxAmt = models.CharField(max_length=10,default="missing")
CalculatedAmt = models.CharField(max_length=10, default="missing")
ProjectCode = models.CharField(max_length=10,default="missing")
Location = models.CharField(max_length=10,default="missing")
Sales_Person = models.CharField(max_length=10,default="missing")
AcCode = models.CharField(max_length=8,default="missing")
Customer_Name = models.CharField(max_length=30,default="missing")
def __str__(self):
return "%s" % self.id
class Salesperson(models.Model):
Sales_Person_P = models.CharField(max_length=10,default="missing",primary_key=True)
Sales_Person_Name = models.CharField(max_length=10,default="missing")
Sales_Person_Contact = models.CharField(max_length=10,default="missing")
def __str__(self):
return "%s" % self.Sales_Person_P
class Account(models.Model):
AcCode_P = models.CharField(max_length=8, default="missing",primary_key=True)
Customer_Name = models.CharField(max_length=30,default="missing")
AcCur = models.CharField(max_length=3, default="missing")
def __str__(self):
return "%s" % self.AcCode_P
Query in shell (for a table):
Transaction.objects.all().filter(Sales_Person=Sales_Person).values('DocRef','DocDate','AcCrIsMinus1','HomeWTaxAmt','ProjectCode','Customer_Name','Location')
Error Message:
django.core.exceptions.FieldError: Cannot resolve keyword 'CalculatedAmt' into field. Choices are: AcCode, AcCrIsMinus1, AcCurWTaxAmt, Customer_Name, DocDate, DocRef, HomeWTaxAmt, Location, ProjectCode, Sales_Person, id
Here's a screenshot of a Transaction instance from the admin interface:
screenshot
Screenshot of the output for python manage.py showmigrations:
screenshot
Screenshot of migrations 0001_initial file
screenshot
Thank you!

This error does not say that the field is missing. The FieldError exception is raised when there is a problem with a model field. This can happen for several reasons:
A field in a model clashes with a field of the same name from an
abstract base class
An infinite loop is caused by ordering
A keyword cannot be parsed from the filter parameters
A field cannot be determined from a keyword in the query parameters
A join is not permitted on the specified field
A field name is invalid A query contains invalid order_by arguments
Just for your information, for a field which does not exist there is a FieldDoesNotExist exception. It is raised by a model’s _meta.get_field() method when the requested field does not exist on the model or on the model’s parents.
The error is because you are fetching all() first then try to filter. When you fetch all you get all fields and then not include CalculatedAmt in your values.
t = Transaction.objects.filter(Sales_Person__iexact=Sales_Person)
t object will be containing all the field of Transaction so no need for .values, you can retrieve them by t.CalculatedAmt for example. P.s. ixact means exact matching without caring for case-sensitiveness.
Moreover, I assume you have tried to connect 2 models together with Sales_Person field. But you are doing it in the wrong way.
You should use one of the OnetoOne, ForeignKey or ManytoMany relationships. I will use ForeignKey assuming that a salesperson can have many transactions but each transaction can only belong to one person.
class Transaction(models.Model):
DocRef = models.CharField(max_length=10,default="missing")
DocDate = models.DateField()
AcCrIsMinus1 = models.CharField(max_length=10,default="missing")
AcCurWTaxAmt = models.CharField(max_length=10,default="missing")
HomeWTaxAmt = models.CharField(max_length=10,default="missing")
CalculatedAmt = models.CharField(max_length=10, default="missing")
ProjectCode = models.CharField(max_length=10,default="missing")
Location = models.CharField(max_length=10,default="missing")
Sales_Person = models.ForeignKey('Salesperson', on_delete=models.CASCADE)
AcCode = models.CharField(max_length=8,default="missing")
Customer_Name = models.CharField(max_length=30,default="missing")
def __str__(self):
return "%s" % self.id
class Salesperson(models.Model):
Sales_Person_P = models.CharField(max_length=10,default="missing",primary_key=True)
Sales_Person_Name = models.CharField(max_length=10,default="missing")
Sales_Person_Contact = models.CharField(max_length=10,default="missing")
def __str__(self):
return "%s" % self.Sales_Person_P

Related

Django a simple query makes me crazy ''int' object is not iterable'

I have two Models:
class MasterData(models.Model):
ID = models.AutoField(primary_key=True)
Companyname = models.CharField('Companyname', max_length=128, blank=True, null=True)
UserID = models.IntegerField('UserID')
class Prefixes(models.Model):
ID = models.AutoField(primary_key=True)
UserID = models.ForeignKey('MasterData', on_delete=models.CASCADE)
InvoiceNoPrefix = models.CharField('InvoiceNoPrefix', max_length=5, blank=True, null=True)
No I want in my view a make a simple objects.get_or_create if you visit the site the first time and no records exist should it create one.
#login_required(login_url='/backend/')
def edit_prefixes(request):
user_id = request.user.id
userfrommasterdata = MasterData.objects.filter(UserID__in=user_id)
prefixes_data = Prefixes.objects.get_or_create(UserID=userfrommasterdata)
And all what I get is a: 'int' object is not iterable
What do I miss? On my MasterData view it's working perfectlit:
#login_required(login_url='/backend/')
def edit_masterdata(request):
user_id = request.user.id
# stamdata_data = get_object_or_404(Stamdata, pk=user_id)
stamdata_data, _ = MasterData.objects.get_or_create(UserID__iexact=user_id, UserID=user_id)
filter() will always give you a QuerySet, even if only a single object matches the query - in this case, it will be a QuerySet containing a single element.
If you know there is only one object that matches your query, you can use the get() method which returns the object directly:
More Information from Django Documentation
try this:
userfrommasterdata = MasterData.objects.filter(UserID=user_id).first()
#login_required(login_url='/backend/')
def edit_prefixes(request):
user_id = request.user.id
userfrommasterdata = MasterData.objects.filter(UserID=user_id).first()
prefixes_data, _ = Prefixes.objects.get_or_create(UserID=userfrommasterdata)

Django - Get objects from the table which do not have a Foreignkey in another table

I am Django rest framework to return the list of objects who do not have a foreign key in another table. what queryset should I write to get those objects.
models.py
class Event(models.Model):
id = models.IntegerField(primary_key=True)
title = models.CharField(max_length=100,default='')
description = models.TextField(blank=True,default='', max_length=1000)
link = models.URLField(null=True)
image = models.ImageField(null=True, blank=True)
organizer = models.CharField(max_length=100, default='')
timings = models.DateTimeField(default=None)
cost = models.IntegerField(default=1,null=True,blank=True)
def __str__(self):
return self.title
class Featured(models.Model):
event = models.ForeignKey(Event, null=True ,on_delete=models.PROTECT, related_name="event")
def __str__(self):
return self.event.title
class Meta:
verbose_name_plural = 'Featured'
views.py
class Upcoming2EventsViewSet(mixins.RetrieveModelMixin,mixins.ListModelMixin,viewsets.GenericViewSet):
serializer_class = Upcoming2Events
def get_queryset(self):
featured_events = Featured.objects.all().values_list('id')
return Event.objects.filter(id__in=featured_events)
# return Event.objects.exclude(id__in=featured_events.event.id)
# # return Event.objects.exclude(id__in = [featured_events.id])
serializers.py
class Upcoming2Events(serializers.ModelSerializer):
id = serializers.CharField(source='event.id')
title = serializers.CharField(source='event.title')
timings = serializers.DateTimeField(source='event.timings')
organizer = serializers.CharField(source='event.organizer')
class Meta:
model = Featured
fields = ['id','title','organizer','timings']
Error
Got AttributeError when attempting to get a value for field `id` on serializer `Upcoming2Events`.
The serializer field might be named incorrectly and not match any attribute or key on the `Event` instance.
Original exception text was: 'RelatedManager' object has no attribute 'id'.
Can you tell me what queryset should I write to get the only objects which are not present in the table Featured?
Also, what should I do to get only the upcoming 2 events from the Event table which are not present in the Featured table?
Note I am not supposed to use any flag value, can you provide some other solutions?
Based on the Informations you wrote here, i would suggest using a flag to determine a featured event. A second Model is useful if you want to provide more Informations on this specific for a featured event
like this:
class Event(models.Model):
id = models.IntegerField(primary_key=True)
title = models.CharField(max_length=100,default='')
description = models.TextField(blank=True,default='', max_length=1000)
link = models.URLField(null=True)
image = models.ImageField(null=True, blank=True)
organizer = models.CharField(max_length=100, default='')
timings = models.DateTimeField(default=None)
cost = models.IntegerField(default=1,null=True,blank=True)
featured = models.BooleanField(default=False)
so you can directly use querysets to get what you want:
Event.objects.exclude(featured=True)
Event.objects.exclude(featured=True).order_by('-timings')[:2]
I would use ModelViewsets directly, hence you will use your model here.
views and serializers would look like this:
views.py
class Upcoming2EventsViewSet(viewesets.ReadyOnlyModelViewSet):
serializer_class = EventSerializer
queryset = Event.objects.exclude(featured=True).order_by('-timings')[:2]
serializers.py
class EventSerializer(serializers.ModelSerilizer):
class Meta:
model = Event
fields = ['id', 'title', 'organizer', 'timings']
As improvement i would provide filters instead of setting up different ViewSets for just filtering querysets.

AttributeError: 'ManyToManyField' object has no attribute 'First_Name'

i encountered the following problem when i try to migrate list of models one of which contains a ManyToMany field.
class Item(models.Model):
File "C:\Users\helin\Downloads\Django\E-commerce\Farmers\Farmersapp\models.py", line 60, in Item
sluger = farmer.First_Name
AttributeError: 'ManyToManyField' object has no attribute 'First_Name'
Below are the models i created.any help is appreciated.Thank you
class Farmer(models.Model):
id = models.AutoField(default=1,primary_key=True)
First_Name = models.CharField(max_length=15)
Last_Name = models.CharField(max_length=15)
def __str__(self):
return self.First_Name+" "+self.Last_Name
def get_farmer(self):
return self.farmer.First_Name+" " +self.farmer.Last_Name
class Item(models.Model):
id = models.AutoField(default=1,primary_key=True)
category = models.CharField(choices=CATEGORY_CHOICES, max_length=6)
price = models.FloatField()
description = models.TextField(blank=True)
image = models.ImageField()
farmer = models.ManyToManyField(Farmer, through='ItemAmount',related_name='item')
sluger = farmer.First_Name
slug = models.SlugField(default=sluger)
def __str__(self):
return self.category
class ItemAmount(models.Model):
farmer = models.ForeignKey(Farmer, on_delete=models.CASCADE)
item = models.ForeignKey(Item, on_delete=models.CASCADE)
quantity = models.IntegerField(default=1)
First, would suggest to take a look at Python style guide, like lowercase attribute names, etc.
Django auto-creates id primary-key field on every model, unless other field is set as primary-key. So, this part can be safely avoided.
get_farmer method - how is it different from str? Also, these are model instance methods ((self)), so there is no self.farmer field on Farmer object - this will fail.
class Farmer(models.Model):
# id AutoFied is created by default by django, so no need to specify
# id = models.AutoField(default=1,primary_key=True)
first_name = models.CharField(max_length=15)
last_name = models.CharField(max_length=15)
def __str__(self):
return self.first_name + " " + self.last_name
farmer = models.ManyToManyField() - as it is ManyToMany, this means many farmers, so it is better to name field farmers, also same applies to reverse relation - Farmer might have multiple items - related_name=items.
sluger - is it a field? Also, it might have many farmers, so which one to pick?
slug - referencing self fields in default is not good idea, better set default in forms.
You can make slug CharField and set its value in save() method for example.
class Item(models.Model):
# id AutoFied is created by default by django, so no need to specify
# id = models.AutoField(default=1,primary_key=True)
category = models.CharField(choices=CATEGORY_CHOICES, max_length=6)
price = models.FloatField()
description = models.TextField(blank=True)
image = models.ImageField()
farmers = models.ManyToManyField(
Farmer,
through='ItemAmount',related_name='items'
)
slug = models.SlugField()
def __str__(self):
return self.category
You can start with minimum working models and add new fields / methods one by one - it would be easier to debug and you will have base working app.

How to send info in URL?

I am trying to create a product filter.
I am sending the user choice in URL
if the user select size = L then using request.GET
I am receiving:
{'size': ['L']}
But I want to receive: {'size':{'op':'in','attri':'L'}}
Is this possible?
Please help
my models are
class ProductAttribute(models.Model):
slug = models.SlugField(max_length=50, unique=True)
name = models.CharField(max_length=100)
op = models.CharField(max_length=20,default='in')
class Meta:
ordering = ('slug', )
def __str__(self):
return self.name
def get_formfield_name(self):
return slugify('attribute-%s' % self.slug, allow_unicode=True)
def has_values(self):
return self.values.exists()
class AttributeChoiceValue(models.Model):
name = models.CharField(max_length=100)
slug = models.SlugField(max_length=100)
attribute = models.ForeignKey(
ProductAttribute, related_name='values', on_delete=models.CASCADE)
class Meta:
unique_together = ('name', 'attribute')
def __str__(self):
return self.name
class Product(models.Model):
name = models.CharField(max_length=128)
attributes = HStoreField(default={})
q2 = AttributeChoiceValue.objects.filter(attribute__name='size')
My size filter(filter.py) is:
size = django_filters.ModelMultipleChoiceFilter(queryset=q2.values_list('name', flat=True).distinct(),widget=forms.CheckboxSelectMultiple)
I am currently using the following query to filter my database in views.py
result = Product.objects.all()
for key, value in request.GET:result = result.filter(**{'attributes__{}__in'.format(key): value})
I want to make it
a=request.GET
for key, value in a:
result = result.filter(**{'attributes__{}__{}'.format(key,a['op']): value})
so that if I even use Price range as filter my query filter accordingly will be
attributes__price__range
You can send info to your views via "path converters":
https://docs.djangoproject.com/en/2.0/topics/http/urls/#path-converters
Or using regular expressions:
https://docs.djangoproject.com/en/2.0/topics/http/urls/#using-regular-expressions

In Django REST framework, how do you access a field in a table referenced by a foreign key

I have the following models in Django:
class campaign(models.Model):
start_date = models.DateField('Start Date')
end_date = models.DateField('End Date')
description = models.CharField(max_length=500)
name = models.CharField(max_length=200)
active_start_time = models.TimeField()
active_end_time = models.TimeField()
last_updated = models.DateTimeField('Date updated',auto_now=True)
active = models.BooleanField(default=True)
client_id = models.ForeignKey('client',on_delete=models.PROTECT)
def __unicode__(self):
return u'%d | %s | %s' % (self.id,self.name, self.description)
class campaign_product(models.Model):
product_id = models.ForeignKey('product',on_delete=models.PROTECT)
last_updated = models.DateTimeField('Date updated',auto_now=True)
campaign_id = models.ForeignKey('campaign',on_delete=models.PROTECT)
class product(models.Model):
name = models.CharField(max_length=200)
description = models.CharField(max_length=500)
sku = models.CharField(max_length=200,blank=True,null=True)
retail_price = models.DecimalField(decimal_places=2,max_digits=11)
discount_price = ((1,'Yes'),(0,'No'))
discounted_price = models.DecimalField(decimal_places=2,max_digits=11,blank=True,null=True)
category_id = models.ForeignKey('category',on_delete=models.PROTECT)
last_updated = models.DateTimeField('Date updated',auto_now=True)
active = models.BooleanField(default=True)
def __unicode__(self):
return u'%d | %s' % (self.id, self.name)
I also have the following serializer:
class campaignProductSerializer(serializers.HyperlinkedModelSerializer):
class Meta:
model = campaign_product
fields = ('product_id', 'campaign_id')
And the following view set behavior in the urls.py file:
class campaignProductViewSet(viewsets.ModelViewSet):
queryset = campaign_product.objects.filter(campaign_id__start_date__lte=datetime.now(),campaign_id__end_date__gte=datetime.now(),campaign_id__active__exact=True)
serializer_class = campaignProductSerializer
My problem is I need to include the name field from the products model in my query results when for instance a request is made on http://127.0.0.1:8000/campaign_product/1/. Currenly this request returns only the product_id and the campaign_id. I tried making the serializer as follows:
class campaignProductSerializer(serializers.HyperlinkedModelSerializer):
class Meta:
model = campaign_product
fields = ('product_id', 'campaign_id', 'product.name')
But then the service returns the following error:
Field name `product.name` is not valid for model `campaign_product`.
I event tried using product__name with and without quotes. Without quotes it tells me that there is no such variable, and with quotes it gives the is not valid for model error similar to the above. Heeelp! Getting this extra field is proving to be a pain :-(
What you want will need to look something more like this:
class campaignProductSerializer(serializers.HyperlinkedModelSerializer):
product_name = serializers.CharField(source='product_id.name')
class Meta:
model = campaign_product
fields = ('product_id', 'campaign_id', 'product_name')
P.S. As an unrelated side note, it is generally a convention in Python code to name classes with CamelCase, such as Campaign, CampaignProduct, Product, and CampaignProductSerializer.
Edit: P.P.S. Originally, I had put written the product_name field with source='product.name'. This was actually due to me looking at the code too quickly and making assumptions based on Django conventions. Typically, with a Django ForeignKey, you would name the ForeignKey field after the model you are linking to, rather than explicitly naming it with _id. For example, the CampaignProduct model would typically be written with product = ForeignKey(...) and campaign = ForeignKey(...). In the background, Django will actually use product_id and campaign_id as the database field names. You also have access to those names on your model instances. But the product and campaign variables on your model instances actually return the objects which you are referring to. Hopefully that all makes sense.