the code did not return all of the item's name based on employee..? how to solve this probem? did the models wrong? or the query?
MODELS.PY
class Employee(models.Model):
name = models.CharField(max_length=100)
telephone_number = models.CharField(max_length=20)
address = models.TextField()
email = models.EmailField()
class Item(models.Model):
code = models.CharField(max_length=4)
name = models.CharField(max_length=100)
kind = models.CharField(max_length=100)
description = models.TextField()
class Inventory(models.Model):
employee = models.ForeignKey(Employee, on_delete=models.CASCADE)
item = models.ForeignKey(Item, on_delete=models.CASCADE)
def get_absolute_url(self):
return reverse('inventaris-detail', kwargs={'pk': self.pk})
VIEWS.PY
how can i get all of the employee's item ?
query_set = Inventory.objects.all()
for query in query_set:
output.append([
query.employee.name,
query.item.name
])
i need something like query.employee.items_set.all() .. ?
You want to get all of the items from an employee? The following should achieve that:
employee = Employee.objects.all()[0] # Just get a random employee, you can do this with more employees too if you want
employees_items = [inventory.item for inventory in employee.inventory_set.all()]
Your code does not logically make a lot of sense though, to be honest. Most likely, there should be a field on a Item class which is a FK to Inventory. Your item class should probably be:
class Item(models.Model):
code = models.CharField(max_length=4)
name = models.CharField(max_length=100)
kind = models.CharField(max_length=100)
description = models.TextField()
inventory = models.ForeignKey(Inventory, on_delete=models.CASCADE)
(Of course this will not work since Inventory is defined after this class, but you can just put Inventory above it or use one of the other many methods to solve this problem)
Good luck!
Related
I am building a Blog App and I am trying to sort or order_by in list which contains multiple queries.
models.py
class BlogPost(models.Model):
user = models.ForeignKey(User, on_delete=models.CASCADE)
title = models.CharField(max_length=30)
date = models.DateTimeField(auto_now_add=True)
class Comments(models.Model):
user = models.ForeignKey(User, on_delete=models.CASCADE)
blog_of = models.ForeignKey(BlogPost, on_delete=models.CASCADE)
body = models.CharField(max_length=30, default='')
date_added = models.DateTimeField(auto_now_add=True)
views.py
def mypage(request):
query_1 = list(BlogPost.objects.filter(user=request.user).order_by('-date'))
query_2 = list(Comment.objects.filter(user=request.user).order_by('date_added'))
results = sorted(chain(query_1, query_2),key=attrgetter('date') , reverse=True)
context = {'results':results}
return render(reques, 'mypage.html', context)
But is showing
'Comment' object has no attribute 'date'
And I think this is because date field name is different in both model and i am sorting with only one, But i have no idea how can I sort with different field name.
Any help would be much Appreciated. Thank You
Or just add it as a property:
class Comments(models.Model): # do NOT give a model a plural name!
# ....
#property
def date(self):
return self.date_added
# or if it is a datetimefield
# return self.date_added.date()
ALso you can just write a more customized sorting key (e.g. in case the involved models are from third-party apps).
def order(obj):
try:
return obj.date
except AttributeError:
return obj.date_added
# ...
results = sorted(chain(query_1, query_2), key=order, reverse=True)
I have two models with One-to-Many relationship; Listing, and Bids.
Is it possible to retrieve and display a list of Bid objects' bid_price in Listing's str method?
The code provided below crashes the server and I am not sure of the correct keywords to search for.
I understand how listing.bid_set works in the Shell or view, but I am not sure how to make it work here.
class Listing(models.Model):
title = models.CharField(max_length=64)
def __str__(self):
bid_objects = Bid.objects.all().filter(listing__id=self.id)
price_list = []
for bid_object in bid_objects:
price_list.append(bid_object.bid_price)
return f"{self.title}, {price_list}"
class Bid(models.Model):
listing = models.ForeignKey(Listing, on_delete=models.CASCADE, related_name="listing_bids")
bid_price = models.DecimalField(max_digits=6, decimal_places=2)
Thanks for your help.
Since you specified related_name='listing_bids', it means you access the related Bids with self.listing_bids:
class Listing(models.Model):
title = models.CharField(max_length=64)
def __str__(self):
bid_objects = self.listing_bids.values_list('bid_price', flat=True)
return f'{self.title}, {bid_objects}'
This question is in relation to project 2 of the cs50 course which can be found here
I have looked at the following documentation:
Django queryset API ref
Django making queries
Plus, I have also taken a look at the aggregate and annotate things.
I've created the table in the template file, which is pretty straight forward I think. The missing column is what I'm trying to fill. Image below
These are the models that I have created
class User(AbstractUser):
pass
class Category(models.Model):
category = models.CharField(max_length=50)
def __str__(self):
return self.category
class Listing(models.Model):
owner = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE)
title = models.CharField(max_length=200)
description = models.TextField()
initial_bid = models.IntegerField()
category = models.ForeignKey(Category, on_delete=models.CASCADE)
date_created = models.DateField(auto_now=True)
def __str__(self):
return self.title
class Bid(models.Model):
whoDidBid = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE)
list_item = models.ForeignKey(Listing, default=0, on_delete=models.CASCADE)
bid = models.IntegerField()
category = models.ForeignKey(Category, on_delete=models.CASCADE)
date = models.DateTimeField(auto_now=True)
def __str__(self):
return_string = '{0.whoDidBid} {0.list_item} {0.bid}'
return return_string.format(self)
This is the closest I could come to after a very long time. But the result I get is just the number 2. Ref image below
Listing.objects.filter(title='Cabinet').aggregate(Max('bid'))
Where 'Cabinet' is a Listing object that I have created. And placed two bids on them.
So the question is, how do I get the Maximum bid value(i.e. 110 for this case) for a particular listing? Using the orm. I think if I used a raw sql query, I could build a dict, send it to the template with the queryset. Then while looping through the queryset, get the value for the key, where the key is the name of the listing or something along those lines. Nah, I would like to know how to do this through the ORM please.
Here's answer #1
Bid.objects.filter(list_item__title='Cabinet').prefetch_related('list_item').aggregate(Max('bid'))
What happens when you try this (sorry, I don't have any objects like this to test on):
Bid.objects.values(list_item__title).prefetch_related('list_item').annotate(Max('bid'))
models.py
class Add_category(models.Model):
Category = models.CharField(max_length=100)
Image = models.ImageField()
MetaKeyword = models.CharField(max_length=100)
MetaDesc = models.CharField(max_length=100)
def __str__(self):
return self.Category
In this, I have tried to add city field and choices must come in this
field by the help of Add_category model but it fails.
class Make_Invoice(models.Model):
Order_no = models.IntegerField()
Invoice_no = models.IntegerField()
Product_name = models.CharField(max_length=100)
Product_Id = models.IntegerField()
Quantity = models.IntegerField()
City = models.CharField(max_length=100, choices = Add_category.Category, default='Select')
Why even use City as a as a CharField? As far as I see it should be a ForeignKey - ManyToOne or even ManyToMany relation.
Check it in the documentation:
https://docs.djangoproject.com/en/2.2/topics/db/examples/many_to_one/
https://docs.djangoproject.com/en/2.2/topics/db/examples/many_to_many/
Use a ForeignKey
City = models.ForeignKey('Add_category', on_delete=models.PROTECT)
I'm trying to get a PurchaseOrder that can be added indefinitely many times. Maybe this is easier than I am thinking, but here is my problem in this imagine:
I would like it to where instead of adding another VendorProfile, it'll add another PurchaseOrder. My end goal is to be able to add 1, 2, 20, etc. PurchaseOrder from the same add screen. Not to be able to add a PurchaseOrder, and then a VendorProfile.
Here's some code: In models.py
class PurchaseOrder(models.Model):
product = models.CharField(max_length=256)
dollar_amount = models.FloatField()
item_number = models.AutoField(primary_key=True)
vendor = models.ForeignKey('VendorProfile')
class VendorProfile(models.Model):
name = models.CharField(max_length=256)
address = models.CharField(max_length=512)
city = models.CharField(max_length=256)
In admin.py
class ProductInline(admin.StackedInline):
model = VendorProfile
extra = 3
class PurchaseOrderAdmin(admin.ModelAdmin):
#...
inlines = [ProductInline]
If I understand you correctly, you whant associate many PurchaseOrder's to one VerndorProfile. In such a case it would be better to use ManyToManyField.
Example:
models.py:
class PurchaseOrder(models.Model):
product = models.CharField(max_length=256)
dollar_amount = models.FloatField()
item_number = models.AutoField(primary_key=True)
def __unicode__(self):
return u'{} {}'.format(self.product, self.dollar_amount)
class VendorProfile(models.Model):
name = models.CharField(max_length=256)
address = models.CharField(max_length=512)
city = models.CharField(max_length=256)
purchased_orders = models.ManyToManyField('PurchaseOrder')
admin.py
class VendorProfileAdmin(admin.ModelAdmin):
filter_horizontal = ('purchased_orders', )
admin.site.register(VendorProfile, VendorProfileAdmin)