Making many-to-many relationships with different price for different customer - django

I have three models Product, Buyer and Offer.
Any buyer can inquire about any kind of Product but for each customer I might offer a different price.
The net price of a product is already given by the supplier.
I wrote the code below and suddenly realized I can only select products for an offersheet but cannot give a different price every time for each product and for each customer with this code.
It would be nice if anyone could give me some suggestions.
Thanks.
class Product(models.Model):
name = models.CharField(...)
net_price = models.NumericField(...)
class Buyer(models.Model):
name = models.CharField(...)
class Offer(models.Model):
date = models.DateTimeField(auto_created=True, auto_now_add=True)
buyer = models.ForeignKey(Buyer, default='',)
products = models.ManyToManyField(Product, related_name='offer',)

You can do it as following:
class Product(models.Model):
name = models.CharField(...)
class Buyer(models.Model):
name = models.CharField(...)
class Offer(models.Model):
date = models.DateTimeField(auto_created=True, auto_now_add=True)
buyer = models.ForeignKey(Buyer)
class OfferUnit(models.Model):
offer = models.ForeignKey(Offer)
product = models.ForeignKey(Product)
net_price = models.IntegerField()
OfferUnit is like one row in your bill(invoice) so you can specify different price for different buyers.

Related

Complex Query from several models in django

I'm trying to query into three models. I need to get the amount products that are in the stores region location. These are my models:
class Store(models.Model):
name = models.CharField(max_length=255)
logo = models.URLField(null=True, blank=True)
user = models.OneToOneField(get_user_model(), models.CASCADE,
related_name="user_store")
region = models.CharField("Departamento", max_length=100)
city = models.CharField("Ciudad", max_length=100)
class Product(models.Model):
name = models.CharField("Nombre del Producto", max_length=255)
description = models.TextField()
stock = models.PositiveIntegerField()
seller = models.ForeignKey(User, on_delete=models.CASCADE)
Product is related with user and it is related to store, what I want to do is something like this:
{
"Risaralda": 1523,
"Cundinamarca": 8541
}
where keys "Risaralda" and "Cundinamarca" are regions and values are the product amount in these places
I tried something like this
products = Product.objects.filter(
seller__user_store__region__in=Store.objects.filter()
.values("region").distinct())
And I got products in stores regions but i need to count how many products are in every store regions
thank you a lot
Something like this should do the trick:
from django.db.models import F
from django.db.models import Count
Product.objects.annotate(region=F('seller__user_store__region')).annotate(num_products=Count('id')).values_list('region', 'num_products')

getting the pk of other model from one model

models.py
class Customer(models.Model):
customer_name = models.CharField(max_length=50)
address = models.CharField(max_length=100)
bill_no = models.CharField(max_length=8)
class Sell(models.Model):
customer = models.ForeignKey(Customer, on_delete=models.CASCADE)
date = models.DateField(auto_now_add=True)
total = models.IntegerField()
vat = models.IntegerField()
How do get the customer id from Sell model/object?
like Sell.objects.get(pk=..)
You can get using foreign key concept.
Here you can get the pk of Customer model using customer field of Sell model, it will be customer__pk.
Similarly customer_name you can get by customer__customer_name and address using customer__address and bill_no using customer__bill_no.
Note: Remember it is fieldnameincurrentmodel__othermodelfieldname, it is the double underscore.
Sell.objects.get(pk=customer__pk)

Django model - how to go about this concept

I have a product model with the following:
class Product(models.Model):
name = models.CharField(max_length=255)
handle = models.CharField(max_length=55)
summary = models.CharField(max_length=255, blank=True)
category = models.ForeignKey(Category)
Above is just the product detail, but there are 3 types of pricing:
Standard - normal regular pricing by filling the price field
Variant - pricing with product variants (size, colour, etc.) with their respective prices
Combined - this is a combination of other saved products, with a custom price provided by user.
For 1 and 2 I have the below model. If the product model has more than 1 price on StandardProduct model then I know it has variants.
class StandardProduct(models.Model):
variant_type = models.CharField(max_length=55)
variant_name = models.CharField(max_lenght=55)
product = models.ForeignKey(Product)
sku = models.CharField(max_length=55, blank=True, null=True)
barcode = models.CharField(max_length=55, blank=True, null=True)
selling_price = models.DecimalField(max_length=15, decimal_places=2)
How do I go about creating the CombinedProduct model? The combined product model can have different created products inside (with their quantities). The price is specified by the user. Below is what I have, but I don't know how to approach this.
class CombinedProduct(models.Model):
product = models.ForeignKey(Product)
item = models.ForeignKey(StandardProduct)
quantity = models.DecimalField(max_length=15, decimal_places=2)
How do I go about creating the CombinedProduct model? The combined
product model can have different created products inside (with their
quantities). The price is specified by the user. Below is what I have,
but I don't know how to approach this.
What you probably want is a ManyToManyField with through option.
This is just a very rough sketch up - I don't get your Product/StandardProduct and the relations.
class CombinedProduct(models.Model):
products = models.ManyToManyField(
Product,
through='Combination'
)
class Combination(models.Model):
product = models.ForeignKey(Product)
combined_product = models.ForeignKey(CombinedProduct)
price = models.DecimalField(max_length=15, decimal_places=2)
quantity = models.DecimalField(max_length=15, decimal_places=2)

How to write a query based on multiple tables?

I want the details of lender whose state,distrtict,religion,profession equals to borrowers details i.e;(state,distrtict,religion,profession)
This is borrowers models.py
class Borrower(models.Model):
district = models.TextField(blank=True)
state = models.TextField(blank=True)
profession = models.TextField(blank=True)
religion = models.TextField(blank=True)
This is Lenders models.py
class LenderStateDistrict(models.Model):
lenderId = models.CharField(max_length=5)
state = models.CharField(max_length=50,**optional)
district = models.CharField(max_length=50,**optional)
class LenderReligion(models.Model):
lenderId = models.CharField(max_length=5)
religion = models.CharField(max_length=50, **optional)
class LenderMultipleProfessions(models.Model):
lenderId = models.CharField(max_length=5)
profession = models.CharField(max_length=50,**optional)
views.py
#api_view(['GET'])
def xyz(request):
borrower1= Borrower.objects.get(id =1)
city = borrower1.district
state = borrower1.state
profession = borrower1.profession
religion = borrower1.religion
I got every requirement for borrower and then how to query based on the three tables i.e; LenderStateDistrict,LenderReligion,LenderMultipleProfessions,if the borrowers district,state,religion,profession equals to the lenders then it should give the details how to query it?
There's a fundamental problem with your models. They are not related to each other. The power of Relational Database Management Systems lies in making relationships!
Django offers ways to define the three most common types of database
relationships: many-to-one, many-to-many and one-to-one.
https://docs.djangoproject.com/en/1.10/topics/db/models/#relationships
At the very least you need to create a foreign key between your borrow and the lender. But it may need to be a ManyToMany relationship if users can borrows from more than one lender
As #e4c5 mentioned that there is a problem with your models, try to relate your models with each other so that writing queries become easier.
Try to implement this way:
class District(models.Model):
field1 = models.CharField(max_length=255)
field2 = models.CharField(max_length=255)
class Religion(models.Model):
field1 = models.CharField(max_length=255)
field2 = models.CharField(max_length=255)
class Profession(models.Model):
field1 = models.CharField(max_length=255)
field2 = models.CharField(max_length=255)
This should be your basic models according to your question, and then you can reference these models in your Lender and Borrower tables, this way:
class Lender(models.Model):
district = models.ForeignKey(District, related_name="lender_district")
profession = models.ForeignKey(Profession, related_name="lender_profession")
religion = models.ForeignKey(Religion, related_name="lender_region")
class Borrower(models.Model):
district = models.ForeignKey(District, related_name="borrower_district")
profession = models.ForeignKey(Profession, related_name="borrower_profession")
religion = models.ForeignKey(Religion, related_name="borrower_region")
This way you can achieve that query that you want. Suppose you want to access the details of Borrower and Lender who belongs to district where field1 = "xyz", for that you have to simply write:
lenders = Lender.objects.filter(district__field1="xyz")
borrowers = Borrower.objects.filter(district__field1="xyz")
And further simple way is:
district = District.objects.get(field1="xyz") # get district
lenders = Lender.objects.filter(district=district) # Get Lenders
borrowers = Borrower.objects.filter(district=district) # Get Borrowers
You can implement ManyToMany relations too if lender and Borrower has more than one District, Religion or Profession.

Django- manytomany model relationships

I'm still learning about how to setup up relational databases. I'm trying to create a db that tracks universities, departments, and their programs. My question is a relationship one. Each university might have one or more departments. This relationship should then be a many to many. Each department may have one or more programs, so I can see the relationship between the department and the programs being many to many.
The problem that I have is if I want to have a department that belongs to a university, I feel like I should use an intermediary to attach a program to that department. But then, if I want to add another program to the same department, I would end up having two of the same departments belonging to the one university. This doesn't seem right.
In other words:
class Department(models.Model):
'''
'''
code = models.CharField(max_length=80,unique=True)
description = models.CharField(max_length=255)
def __unicode__(self):
return '{}'.format(self.description)
class Universities(models.Model):
'''
'''
code = models.CharField(max_length=80,unique=True)
description = models.CharField(max_length=255)
departments = models.ManyToManyField(Department,through='UniversityHasDepartment')
class Program(models.Model):
'''
'''
code = models.CharField(max_length=80,unique=True)
description = models.CharField(max_length=255)
def __unicode__(self):
return '{}'.format(self.description)
class UniversityHasDepartment(models.Model):
university = models.ForeignKey(Universities)
department = models.ForeignKey(Department)
program = models.ForeignKey(Program)
I think you want to use foreign keys. (one to many relationships).
Each university can have multiple departments but a department can only have 1 university.
Each department can have multiple programs but a program can only have 1 department.
class University(models.Model):
name = models.CharField(max_length=80,unique=True)
description = models.CharField(max_length=255)
class Department(models.Model):
university = models.ForeignKey(University, related_name='departments')
name = models.CharField(max_length=80,unique=True)
description = models.CharField(max_length=255)
class Program(models.Model):
department = models.ForeignKey(Department, related_name='programs')
name = models.CharField(max_length=80,unique=True)
description = models.CharField(max_length=255)