Show two tables specific column data into one list? - django

I have two tables Customer and Subscription in which Customer has the list of customers and Subscription contains the Customer and Packages.
In the customer list i want to show how many packages each customer has.
Subscription Model
class Subscription(models.Model):
client = models.ForeignKey(Customer, on_delete=models.SET_NULL, blank=True, null=True, related_name="subscriptions")
package = models.ForeignKey(Package, on_delete=models.SET_NULL, blank=True, null=True)
valid_start_date = models.DateTimeField()
valid_end_date = models.DateTimeField()
usage_count = models.IntegerField(null=True)
status = models.CharField(max_length=20)
transaction = models.BigIntegerField(blank=True, null=True, default=0)
created_at = models.DateTimeField()
updated_at = models.DateTimeField()
Customer Model
class Customer(AbstractBaseUser):
first_name = models.CharField(max_length=250, blank=True, null=True)
last_name = models.CharField(max_length=250, blank=True, null=True)
email = models.EmailField(unique=True, blank=True, null=True)
mobile_number = models.BigIntegerField(blank=True, null=True)
password = models.CharField(max_length=1000, blank=True, null=True)
gender = models.CharField(max_length=10, blank=True, null=True)
profile_picture = models.ImageField(upload_to="user_data/profile_picture", blank=True)
address = models.CharField(max_length=500, blank=True, null=True)
country = models.ForeignKey(Countries, on_delete=models.SET_NULL, blank=True, null=True)
state = models.ForeignKey(States, on_delete=models.SET_NULL, blank=True, null=True)
city = models.ForeignKey(Cities, on_delete=models.SET_NULL, blank=True, null=True)
pincode = models.IntegerField(blank=True, null=True)
number_of_logins = models.IntegerField(blank=True, null=True)
is_active = models.BooleanField(default=True)
created_at = models.DateTimeField(blank=True, null=True)
updated_at = models.DateTimeField(blank=True, null=True)
USERNAME_FIELD = "email"
Expected Result : I want to show the package field data from Subscription Model into the list of Customer model.
name - no. - emaiId- pakages_subbed
customer1 - mobile - email - package1,package2
customer2 - mobile - email - package4,package1
Actual Result : Only Customer field data

You need to use annotate in your queryset much as here
I think
query = Customer.objects.annotate(subscription_count=Count('subscriptions'))
ought to do it (with the count available as object.subscription_count for any object retrieved from this query)
This is just one database query, returning only Customer objects, whereas {{ customer.subscriptions.all|length }} will be a lot of them (and will probably also retrieve all the Subscription objects just to count them).
If you wanted greater access to the Subscription and Package objects you could do
Subscription.objects.all().order_by("client__id", "package__name")...
(I made up "package__name") which should get you the subscriptions grouped firstly by customer and then ordered by package name for each customer.

Related

Get all items from one model on condition that is in other model

Hi i was snooping around stack but answers are confusing or not working, you can see my models how can I get all OrderItems made by user that have complete=True in Order.
class Order(models.Model):
customer = models.ForeignKey(Customer, on_delete=models.SET_NULL, blank=True, null=True)
date_oredred = models.DateField(auto_now_add=True)
complete = models.BooleanField(default=False, null=True, blank=True)
transaction_id = models.CharField(max_length=200, null=True)
class OrderItem(models.Model):
product = models.ForeignKey(Product, on_delete=models.SET_NULL, blank=True, null=True)
order = models.ForeignKey(Order, on_delete=models.SET_NULL, blank=True, null=True)
quantity = models.IntegerField(default=0, null=True, blank=True)
date_added = models.DateTimeField(auto_now_add=True)
transaction_id = models.CharField(max_length=200, null=True)
Use the following:
qs = OrderItem.objects.filter(order__complete=True)
To get for specific customer:
qs.filter(order__customer=specific_customer)

Adding assigner and assignee in Django

I am fairly new to django rest framework, and I am trying to make a model which is associated with two users, one as assigner and the other as assignee. I tried adding two different foreign keys, but it throws error. Here is my code:
job = models.ForeignKey(Job,related_name='Job',on_delete=models.CASCADE, null=True)
assigner = models.ForeignKey(User, on_delete=models.PROTECT, null=True)
assignee = models.ForeignKey(User, on_delete=models.PROTECT, null=True)
unit = models.ForeignKey(Unit,related_name='UnitName',on_delete=models.CASCADE, null=True)
equipment = models.ForeignKey(Equipment,related_name='EquipmentName',on_delete=models.CASCADE, null=True)
name = models.CharField(max_length=200)
category = models.CharField(max_length=200, null=True,blank=True)
start_date = models.DateField()
end_date = models.DateField()
created_at = models.DateTimeField(auto_now_add=True,blank=True, null=True)
updated_at = models.DateTimeField(auto_now=True,blank=True, null=True)
status = models.ForeignKey(TaskStatus, related_name='Status',on_delete=models.CASCADE)
def __str__(self):
return(self.name)
Please help

Django: Select matching foreign keys during filter

We have the following example models and are wondering if it's possible to select the foreign keys that match during the same query, possibly as an annotation.
class BaseProduct(models.Model):
date_created = models.DateTimeField(auto_now_add=True)
date_updated = models.DateTimeField(auto_now=True)
name = models.CharField(max_length=255)
sub_title = models.CharField(max_length=255, blank=True, null=True)
identifier_retailer = models.CharField(max_length=255)
tags = models.CharField(max_length=255, blank=True, null=True)
has_multiple_variants = models.BooleanField(default=False)
class BaseProductVariant(models.Model):
product = models.ForeignKey(BaseProduct)
name = models.CharField(max_length=128, blank=True, null=True)
sub_title = models.CharField(max_length=255, blank=True, null=True)
date_created = models.DateTimeField(auto_now_add=True)
date_updated = models.DateTimeField(auto_now=True)
description = models.TextField(blank=True, null=True, help_text='Product description')
features = models.TextField(blank=True, null=True, help_text='One feature per line')
content = RedactorField(allow_image_upload=True, allow_file_upload=True, blank=True, null=True, help_text='Use this for rich HTML on featured products')
warranty_string = models.CharField(max_length=255, blank=True, null=True)
identifier_retailer = models.CharField(max_length=255, blank=True, null=True)
identifier_upc = models.CharField(max_length=255, blank=True, null=True)
identifier_model = models.CharField(max_length=255, blank=True, null=True)
We can query the results easily with BaseProduct.objects.filter()... but would like to select the list of matching BaseProductVariant's at the same time, otherwise we have to query the database in an unconventional fashion, and joining in python with prefetch_related on BaseProductVariant.objects.filter(product__in=[]).prefetch_related(product), select_related works on this too, but it a bit slower due to the extra deserialization on each row.
You can use prefetch_related from BaseProduct to prefetch the variants with the related name. You can also use the Prefetch[1] object from django.db.models to control the attribute name where the prefetched variants end up:
from django.db.models import Prefetch
products_with_variants = BaseProduct.objects.all().prefetch_related(
Prefetch('baseproductvariant_set', to_attr='variants'))
for p in products_with_variants:
print(p.variants)
[1] https://docs.djangoproject.com/en/2.2/ref/models/querysets/#django.db.models.Prefetch

Can`t manually delete record from sqlite table, because related table with __old does not exists

I want to manually delete records from sqlite table(witch was created with Django 1.10, Table from i want to delete records called main.storage_claim, it has relation to main.storage_claimlist), but got error: Error deleting record: no such table: main.storage_claimlist__old.
I dont know why it want this table.
I have only main.storage_claimlist without __old.
Btw, i`m using DB Browser for SQLite as gui tool for working with sqlite.
Can someone explain what the heck is __old?
ClaimList model:
class ClaimList(models.Model):
""" Claim list contains one to many claim. Used for grouping claims. """
created_at = models.DateTimeField(default=datetime.now, blank=True, null=True)
from_storage = models.ForeignKey(
Storage, related_name='from_storage', blank=True, null=True, default=True)
to_storage = models.ForeignKey(
Storage, related_name='to_storage', blank=True, null=True, default=True)
status = models.CharField(max_length=255, blank=True, null=True)
separation = models.CharField(max_length=255, blank=True, null=True)
insurance_company = models.ForeignKey(
InsuranceCompany, null=True, blank=True)
patient = models.CharField(max_length=255, blank=True, null=False)
Claim model:
class Claim(models.Model):
""" Claim contain information about what need to be transefer """
medicine = models.CharField(max_length=255, blank=True, null=True)
claim_list = models.ForeignKey(ClaimList, blank=True, null=True)
requested_amount = models.DecimalField(
default=0, max_digits=5, decimal_places=0)
given_amount = models.DecimalField(
default=0, max_digits=5, decimal_places=0)
requested_unit = models.CharField(max_length=100, blank=True, null=True)
given_unit = models.CharField(max_length=100, blank=True, null=True)
from_income = models.ForeignKey(Income, blank=True, null=True)
status = models.CharField(max_length=100, blank=True, null=True)
is_will_be_accepted_in_future = models.BooleanField(default=False)
price = models.DecimalField(null=True, max_digits=10, decimal_places=5)
sum = models.DecimalField(null=True, max_digits=10, decimal_places=5)
objects = ClaimManager()

Django send email alerts automatically when keywords matches to his profile

Send an email alert whenever newly created profile matches to his search term. I have two module recruiter and seeker. Recruiter can posted their jobs and Seeker can posted their profile. If recruiter searches the seeker's profile based on city name, keyskills,industry type etc.. The searched result can be saved because for future use. If any new seeker's profile matches that searched result which is saved previously it automatically send email to recruiter. This alert has been send everytime when new seeker can matched that recruiter search terms.
Recruiter table
class jobs(models.Model):
user = models.ForeignKey(User)
title = models.CharField(max_length=100)
jobsummary = models.TextField()
industry = models.CharField(max_length=100)
functionalarea = models.CharField(max_length=100)
min_exp = models.IntegerField(default=0)
max_exp = models.IntegerField(default=0)
class employerkeyskills(models.Model):
user = models.ForeignKey(User)
job=models.ForeignKey(jobs, unique=False)
keyskills=models.CharField(max_length=50)
class RecSaveSearch(models.Model):
user = models.ForeignKey(User)
employer=models.ForeignKey(User,unique=False)
searchname=models.CharField(max_length=100,blank=True)
savedsearch=models.CharField(max_length=400, blank=True)
Jobseeker Profile Table
class JSPersonal(models.Model):
user = models.ForeignKey(User)
name=models.CharField(max_length=100, blank=True, null=True)
email = models.EmailField(max_length=100, blank=True, null=True)
city = models.CharField(max_length=100, blank=True, null=True)
work_expyears = models.CharField(max_length=100, blank=True, null=True)
work_expmonths = models.CharField(max_length=100, blank=True, null=True)
salaryrange = models.CharField(max_length=50, blank=True, null=True)
industry = models.CharField(max_length=100, blank=True, null=True)
class JSSkills(models.Model):
user = models.ForeignKey(User)
skill = models.CharField(max_length=100, blank=True, null=True)
version = models.CharField(max_length=100, blank=True, null=True)
lastused = models.CharField(max_length=100, blank=True, null=True)
skillyear = models.CharField(max_length=100, blank=True, null=True)
skillmon = models.CharField(max_length=100, blank=True, null=True)