Django queryset for DRF view - django-models

I have model called Category where we can add the categories and the records will be a manytomanyfield to Records Model what can my queries be to display all the categories on one page and the if i click on the particular category i should get only records related to that particular category.
models.py
class Category(models.Model):
name = models.CharField(max_length=255, blank=True)
records = models.ManytoManyField(Record)
class Record(models.Model):
name = models.CharField(max_length=255, blank=True)
views.py
class CategoryListView(ListAPIView):
def get_queryset(self):
queryset = ?
return queryset
class RecordListView(ListAPIView):
def get_queryset(self):
queryset = ?
return queryset
/categories/page/
Category 1
Category 2
Category 3
Category 4
/Category/Records/page/
Category 1
record 1
record 2
record 3

Related

How to use particular field of a model into another model, like I want to use sku as a foreign key in next model?

class Product(models.Model):
price=models.IntegerField()
no=models.IntegerField(default=0,null=True)
sku= models.CharField(max_length=100,default=0,null=True )
#Here I want to use sku into another model as a foreign key
In that case, the sku needs to be unique, and non-nullable, since otherwise it can not refer to a product properly, so:
class Product(models.Model):
price = models.IntegerField()
no = models.IntegerField(default=0, null=True)
sku = models.CharField(max_length=100, unique=True)
Then you can work with the to_field=… parameter [Django-doc]:
class Order(models.Model):
product = models.ForeignKey(Product, to_field='sku', on_delete=models.CASCADE)
Then if you use my_order.product_id, it will contain the sku of the product it refers to.

How to write a Django model form to include selected fields from multiple tables

There are many questions about building model forms from multiple tables, but I couldn't find a solution to my problem.
Background:
In model.py I have 3 simple models with 1-many relationship
class site(models.Model):
id = models.UUIDField(default=uuid.uuid4, unique=True, primary_key=True, editable=False)
sitename = models.CharField(max_length=150)
site_address = models.CharField(verbose_name='Address', max_length=200, null=True, blank=True)
class block(models.Model):
id = models.UUIDField(default=uuid.uuid4, unique=True, primary_key=True, editable=False)
blockname = models.CharField(max_length=150)
sitename = models.ForeignKey(site, on_delete=models.CASCADE, )
class quarter(models.Model):
id = models.UUIDField(default=uuid.uuid4, unique=True, primary_key=True, editable=False)
quartername = models.CharField(max_length=150)
blockname = models.ForeignKey(block, on_delete=models.CASCADE, )
I have separate forms for each model - where user can add, edit and delete and site, block using standard djando modelform and modelformset.
The challenge I'm facing is with creating a quarter form. On a quarter from I want user to select a site from drop-down, which will populate block and then use can enter quarter name and save submit.
Now, 1 possible solution is to include site as FK in quarter and that will solve the problem - but I don't want to do that. I even tried create separate form instances and call it in view and template - but the problem with this solution is that the mandatory field name from site are also displayed.
How can I show the sitename dropdown on quarter form - where on selecting sitename the user is shown corresponding blockname. On click of save button the data for quarter is saved in db (don't have to save site or block data because we already have those entries)
Any suggestion on approach or solution?

Filtering down through multiple ForeignKey relations in django

I am trying to get down through multiple-foreign key relationship where each Hotel has many Rooms, each Room has many Rateplans, each Rateplan has many Prices.
It resembles Christmas tree if you think about it:
Hotel
v
Room
v
Rateplan
v
Prices
How can I execute query that will return hotels in certain hotel_city on certain price_date, certain price_price and certain price_availability? (just like Expedia or booking.com query)
For example:
Hotel.objects.filter(city='Beirut').filter(room__name=Room.objects.filter(rateplan__name=Rateplan.objects.filter(prices__availability=Prices.objects.filter(availability=1))))
I have looked into django complex queries documentation and annotate/aggregate but couldn't wrap my head around it.
My models below:
class Hotel(models.Model):
name = models.CharField(max_length=64)
city = models.CharField(max_length=64, default='Warsaw')
class Room(models.Model):
hotel_id = models.ForeignKey(Hotel, on_delete=models.CASCADE, related_name='room')
name = models.CharField(max_length=64, default='Double')
class Rateplan(models.Model):
room_id = models.ForeignKey(Room, on_delete=models.CASCADE, related_name='rateplan')
name = models.CharField(max_length=64, default='Standard')
class Prices(models.Model):
rateplan_id = models.ForeignKey(Rateplan, on_delete=models.CASCADE, related_name='prices')
date = models.DateField()
price_1 = models.DecimalField(null=False, max_digits=7, decimal_places=2)
price_2 = models.DecimalField(null=False, max_digits=7, decimal_places=2)
availability = models.SmallIntegerField()```
You can use __ to filter the values you need across relationships
There are good examples in the documentation
Hotel.objects.filter(
city=your_city,
room__rateplan__prices__date=your_date,
room__rateplan__prices__price_1=your_price,
room__rateplan__prices__availability=your_availability,
).distinct()

Join two models in django

I have two models with a unique key: EMAIL. For both of the models the field EMAIL is unique, but some of the emails of model A do not necessarily exist in model B. I would like to perform an inner join, but since I'm quite new to Django I have no idea how to do this.
You should define the Email model look like this
class Email(models.Model):
"""
Email model.
"""
email = models.EmailField(
unique=True,
error_messages={
'unique': "This email has already been registered."
}
)
def __str__(self):
return self.email
Then create 2 models related to Email model by using ForeignKey.
Or you just need to save email by using EmailField for each model.
class ModelA(models.Model):
"""
A model.
"""
email = models.EmailField(
verbose_name="Email",
unique=True,
)
...other fields
In Django, you need to make a relation between table in order to apply any type of join
class ModelA(models.Model):
email = models.EmailField(unique=True)
model_b = models.ForeignKey(to=ModelB, null=True, blank=True)
class ModelB(models.Model):
email = models.EmailField(unique=True)
then
data = ModelA.objects.filter(model_b__isnull=False)
Instance with same email id should be linked with each other.

How to merge two models in django

I have two models with foreign key.
class Ad(models.Model):
town = models.CharField(max_length=30)
owner = models.ForeignKey(SpaUser, on_delete=models.CASCADE) #My foreign key
contact = SpaUser.objects.filter(email= 'owner').values('firstname ') # I want to access SpaUser.firstname to display in django admin
class SpaUser(models.Model):
email = models.EmailField(verbose_name='email address', max_length=255, unique=True)
firstname = models.CharField(max_length=30, blank=True)
lastname = models.CharField(max_length=30, blank=True)
I use Ad.contact in Ad model to acess SpaUser.firstname in Spauser model but i can't.
Help me please
You can make contact a property instead (and you should make use of the foreign key owner instead of filtering from another queryset of SpaUser):
class Ad(models.Model):
#property
def contact(self):
return self.owner.firstname

Resources