Converting List to QuerySet Django - python

models.py
class Part(models.Model):
series = models.CharField(max_length=100)
number = models.CharField(max_length=100)
brand = models.CharField(max_length=100)
class Request(models.Model):
part_number = models.ForeignKey(Part, on_delete=models.CASCADE)
brand = models.CharField(max_length=100)
quantity = models.PositiveIntegerField()
date = models.DateField()
class Quota(models.Model):
part_number = models.ForeignKey(Part, on_delete=models.CASCADE)
brand = models.CharField(max_length=100)
quantity = models.PositiveIntegerField()
price = models.DecimalField(max_digits=10, decimal_places=2)
supplier = models.CharField(max_length=100)
date = models.DateField()
views.py
def requests_and_quotas(request):
requests = Request.objects.all()
quotas = Quota.objects.all()
result = []
for req in requests:
match = False
for quo in quotas:
if (req.part_number.series == quo.part_number.series) and (abs((req.date - quo.date).days) <= 2):
result.append({'request': req, 'quota': quo})
if not match:
result.append({'request': req, 'quota': None})
return render(request, 'requests_and_quotas.html', {'result': result,})
I wanted to connect django_filters, but ran into a problem AttributeError: 'list' object has no attribute '_meta'. How can I change the logic of my code to retrieve a QuerySet object?
result_qs = QuerySet(result) it didn't help

You can create a list of ids of your objects in the list. Then simply filter by them.
instances = [<MyModel: 1>, <MyModel: 2>]
list_of_ids = [inst.id for inst in instances]
queryset = MyModel.objects.filter(id__in=list_of_ids)

Related

Get data from Inherit Model Django

Im working in my Python Django ecommerce project.Now i have 2 classes Item and BookItem :
class Item(models.Model):
item_name = models.CharField(max_length=200, unique=True)
slug = models.SlugField(max_length=200,unique=True)
description = models.TextField(max_length=500, blank=True)
price = models.IntegerField()
images = models.ImageField(upload_to='photos/products')
stock = models.IntegerField()
is_available = models.BooleanField(default = True)
category = models.ForeignKey(Category,on_delete = models.CASCADE)
created_date = models.DateTimeField(auto_now=True)
modified_date= models.DateTimeField(auto_now=True)
def __str__(self):
return self.item_name
def get_url(self):
return reverse('item_detail',args=[self.category.slug, self.slug])
class BookItem(Item):
book = models.ForeignKey(Book,on_delete = models.CASCADE)
I want to get BookItem data from the class Item.Anyone knows how to do it ?
Get Book data for all Items
Item.objects.all().values(
"book__book_name",
"book__import_price",
# "class_name__field_name", structure of the query
)
To filter Item data using Book fields
[filter Items where book name is 'bookname']
Item.objects.filter(book__book_name="bookname")

Shopping cart DB not showing number of Individual Items Ordered

I'm trying to create a shopping cart model, I've created the Order Model, OrderItem model and Also the Item model. Although I find it difficult to link the order it model to the order in the API view.
here's the Model
class Pizza(models.Model):
id = models.AutoField(primary_key=True)
name = models.CharField(max_length=60)
desc = models.CharField(max_length=150)
price = models.IntegerField()
url = models.CharField(max_length=250)
def __str__(self):
return self.name
class OrderItem(models.Model):
id = models.AutoField(primary_key=True)
product = models.ForeignKey("Pizza", on_delete=models.CASCADE, null=True)
date_added = models.DateTimeField(auto_now=True)
date_ordered = models.DateTimeField(null=True)
amount = models.IntegerField(null=True)
def __str__(self):
return self.product.name
class Order(models.Model):
id = models.AutoField(primary_key=True)
name = models.CharField(max_length=60)
email = models.CharField(max_length=150)
address = models.CharField(max_length=150)
total = models.IntegerField()
created_at = models.DateTimeField(default=timezone.now)
items = models.ManyToManyField(OrderItem)
def __str__(self):
return self.name
//The viewset
class OrderViewSet(viewsets.HyperlinkedModelSerializer):
# permission_classes = [IsPostOrIsAuthenticated,]
serializer_class = OrderSerializer
queryset = Order.objects.all().order_by('-created_at')
Currently, I cant display the amount attribute of the order item in my API, It just shows the id and Also the link to the individual orderitem in an order
I think for cart you can use external fields on relations between Order and Pizza. Documentation about this here
Your models looks like:
class Pizza(models.Model):
name = models.CharField(max_length=60)
desc = models.CharField(max_length=150)
price = models.IntegerField()
url = models.CharField(max_length=250)
def __str__(self):
return self.name
class Order(models.Model):
name = models.CharField(max_length=60)
email = models.CharField(max_length=150)
address = models.CharField(max_length=150)
total = models.IntegerField()
created_at = models.DateTimeField(auto_now=True)
items = models.ManyToManyField(Pizza, through='OrderItem')
def __str__(self):
return self.name
class OrderItem(models.Model):
product = models.ForeignKey('Pizza', on_delete=models.CASCADE, null=True)
order = models.ForeignKey('Order', on_delete=models.CASCADE, null=True)
date_added = models.DateTimeField(auto_now=True)
date_ordered = models.DateTimeField(null=True)
amount = models.IntegerField(null=True)
def __str__(self):
return self.product.name
Example, how you can get dict of items amount in order:
order = Order.objects.filter('-created_at').first() // get last order
cart = {item.pk: item.amount for item in order.items}

Django - Join 3 tables to get records

Need to join these 3 tables , can someone give me the ORM queryset . need to show the records on one template based on these three tables.
Models.py
class Item_Table(models.Model):
id = models.AutoField(primary_key=True)
name = models.CharField(max_length=127)
description = models.TextField(null=True,blank=True)
qty_in_ferma_warehouse = models.IntegerField(null=True,blank=True,default=0)
status = models.BooleanField()
ListID = models.CharField(max_length=80, null=True,blank=True)
class Order_Table(models.Model):
id = models.AutoField(primary_key=True)
order_number = models.CharField(max_length=63)
notes = models.TextField()
created_at = models.DateField()
status = EnumField(Choice,max_length=2, null=True,blank=True)
Total_Amount = models.DecimalField(max_digits=18,decimal_places=2)
must_fill_in_items = models.IntegerField()
total_replenish_small_order = models.IntegerField()
order_type = EnumField(Choice3,max_length=2, null=True,blank=True)
delivery_method = EnumField(Choice6, max_length=2, null=True, blank=True)
class Orderitems_Table(models.Model):
id = models.AutoField(primary_key=True)
order_id = models.ForeignKey(Order_Table,on_delete='')
item_id = models.ForeignKey(Item_Table,on_delete='')
qty = models.IntegerField()
next_order_qty = models.IntegerField(null=True,blank=True,default=0)
Rate = models.DecimalField(max_digits=18,decimal_places=2)
Amount = models.DecimalField(max_digits=18,decimal_places=2)
status = EnumField(Choice2,max_length=2,null=True,blank=True)
accumulated_residual_item = models.IntegerField()
accumulated_damaged_item = models.IntegerField()
You can have a many to many field in Order_Table.
items = models.ManyToManyField(Person, through='Orderitems_Table')
then you can query on Order_Table model and have a queryset
you can go through the documentation to have more insights about ManyToMany Field and how to play with this
For forms and view you can follow this link

Django AttributeError:'Campaign' object has no attribute 'ads'

I am trying to create in a nested serializer in Django Rest Framework but I keep getting this error. I know why it's throwing it but, i thought Django would handle the one-to-many relationship.
AttributeError at /api/campaigns
Got AttributeError when attempting to get a value for field ads on serializer CampaignSerializer.
The serializer field might be named incorrectly and not match any attribute or key on the Campaign instance.
Original exception text was: 'Campaign' object has no attribute 'ads'.
class Campaign(models.Model):
name = models.CharField(max_length = 30)
type = models.CharField(max_length = 20)
start_date = models.DateField(auto_now=False, auto_now_add=True)
end_date = models.DateField(auto_now=False, auto_now_add=True)
locations = models.CharField(max_length = 30)
budget = models.IntegerField()
land_page = models.URLField()
keywords = models.TextField()
CPM = models.IntegerField()
CPC = models.IntegerField()
description = models.TextField()
commission = models.IntegerField()
pay_off = models.IntegerField()
advertiser = models.ForeignKey(User)
date_time = models.DateField(auto_now=False, auto_now_add=True)
class Meta:
db_table = "campaigns"
class ADS(models.Model):
advertiser = models.ForeignKey(User)
campaign = models.ForeignKey(Campaign)
headline = models.CharField(max_length=50)
description_1 = models.TextField(blank=True)
description_2 = models.TextField(blank=True)
display_url = models.URLField(blank=True)
final_url = models.URLField(blank=True)
mobile_url = models.URLField(blank=True)
class Meta:
db_table = "ads"
These are my serializers
class ADSerializer(serializers.ModelSerializer):
adsImages = AdsImagesSerializer(read_only=True,many=True)
class Meta:
model = ADS
fields = ("headline","description_1","description_2","display_url","final_url","mobile_url","advertiser","adsImages")
class CampaignSerializer(serializers.ModelSerializer):
advertiser = AdvertiserProfile(read_only=True,required=False)
ads = ADSerializer(many=True)
class Meta:
model = Campaign
fields = ("name","type","start_date","end_date","locations","budget","land_page","keywords","CPM","CPC","description","commission","pay_off","ads","advertiser",)
def get_validation_exclusions(self, *args, **kwargs):
exclusions = super(CampaignSerializer,self).get_validation_exclusions()
return exclusions + ['advertiser']
def create(self, validated_data):
ads_data = validated_data.pop('ads')
campaign = Campaign.objects.create(**validated_data)
for ad_data in ads_data:
ADS.objects.create(campaign=campaign, **ad_data)
return campaign
I just fixed this, with a related name in the model
campaign = models.ForeignKey(Campaign, related_name="ads")
I think it didn't worked last time because the reverse relationship was not working without a related_name.

Getting other tables Django filter/select_related

I am trying to filter values using Django's filter and select_related. I am able to get the base item, but I can't get any of the joined fields.
item = Items.objects.filter(tests__company_user_id__user_id=user_id).filter(item_id=item_id).select_related("tests__company_user").values()
My goal is to get data from the user associated with the item onto the item return. Is this possible?
The data model looks like this:
class Items(models.Model):
item_id = models.CharField(primary_key=True,max_length=100)
mailed_date = models.DateTimeField()
received_date = models.DateTimeField()
last_viewed = models.DateTimeField()
dateitemsent = models.DateTimeField()
itemsent = models.CharField(max_length=25)
itemret = models.CharField(max_length=25)
dateitemret = models.DateTimeField()
status = models.CharField(max_length=25)
class Tests(models.Model):
tests_id = models.CharField(primary_key=True, unique=True, max_length=100)
teststypetest_id = models.ForeignKey(TestsType)
dateitemord = models.DateTimeField()
testdate = models.DateTimeField()
teststypetest_id = models.ForeignKey(TestsType)
dateitemord = models.DateTimeField()
testdate = models.DateTimeField()
status = models.CharField(max_length=100)
item_id = models.ForeignKey(Kits)
company_user_id = models.ForeignKey(CompanyUser)
class CompanyUser(models.Model):
user_id = models.CharField(primary_key=True,max_length=100)
username = models.CharField(max_length=254,default="empty")
sec_question_1 = models.CharField(max_length=254)
sec_answer_1 = models.CharField(max_length=254)
sec_question_2 = models.CharField(max_length=254)
sec_answer_2 = models.CharField(max_length=254)
sec_question_3 = models.CharField(max_length=254)
sec_answer_3 = models.CharField(max_length=254)
When you use select_related() you are caching joined object info but not retrieving, you need explicitly pull data:
item = Items.objects.filter(tests__company_user_id__user_id=user_id).filter(item_id=item_id).select_related("tests__company_user").values("tests__company_user_id__sec_question_1", "tests__company_user_id__sec_question_2", ...)
EDIT
Let's suppose you just want 2 fields from CompanyUser: sec_question_1 and sec_question_2:
from django.db.models import F
item = Items.objects.filter(tests__company_user_id__user_id=user_id).filter(item_id=item_id).select_related("tests__company_user").values().annotate(q1=F('tests__company_user_id__sec_question_1'), q2=F('tests__company_user_id__sec_question_2'))

Categories