How to perform query in Django - django

I need to filter the a particular user's bar in whcih reservations were made. I am a beginner in Django and have tried some methods which unfortunately didn't work.
models.py
class User(AbstractBaseUser, PermissionsMixin):
email = models.EmailField(max_length=254, unique=True)
class Bar(models.Model):
user_id = models.OneToOneField(User, on_delete=models.CASCADE)
name = models.CharField(max_length=50)
def __str__(self):
return self.name
class Tables(models.Model):
table_no = models.CharField(max_length=14, unique=False)
bar = models.ForeignKey(to=Bar, on_delete=models.CASCADE)
def __str__(self):
return self.table_no
class Reservation(models.Model):
first_name = models.CharField(max_length=200)
table = models.ForeignKey(Tables, on_delete=models.CASCADE)
def __str__(self):
return self.first_name
Note: I wan to filter the reservations made in a particular user's bar

I know you might be having a hard time and its one the things you go through when you are learning..
1.Can you change this first
from
class Bar(models.Model):
user_id = models.OneToOneField(User, on_delete=models.CASCADE)
name = models.CharField(max_length=50)
def __str__(self):
return self.name
To
class Bar(models.Model):
user_id = models.ForeignKey(User, on_delete=models.CASCADE)
name = models.CharField(max_length=50, null=True)
def __str__(self):
return self.name
2.On querying your data can you can try this since our user will already on the bar
user_bar = Bar.objects.filter("Here you specify what you wanna filter by")
Or
user_bar = Bar.objects.get(id=pk)

When I used this query filter. it worked perfectly.
reservations = Reservation.objects.filter(table__bar__user_id=request.user)
subject title: People can come to the restaurant and book a reservation filling a form which uses the Reservation model. Then the reservation is connected to a Table which is connected to a bar and the owner of the bar. Now I need to be able to filter the reservations made in each bar owner restaurant.

Related

How do I get a value from a different model in django?

Im new to django and im trying to figure out how to set the value in a model = to a value in another model
from django.db import models
from django.contrib.auth.models import User
class Company(models.Model):
user = models.ForeignKey(User, on_delete=models.CASCADE, null=True)
name = models.CharField(max_length=100, null=True, blank=True) # This is the value I want
_id = models.AutoField(primary_key=True, editable=False)
def __str__(self):
return self.name
class Product(models.Model):
company = models.ForeignKey(Company, on_delete=models.CASCADE, null=True)
companyName = # I want the name here
_id = models.AutoField(primary_key=True, editable=False)
def __str__(self):
return self.name
I've tried these but they dont work
companyName = Company.name
companyName = models.CharField(Company.name, max_length=100, null=True, blank=True)
Company.name will not work because Company is a class, a template for making many Company objects, each with it's own name, so which Company object, or instance, do you want?
You need to get the particular Company first, and then you can set the companyName of the Product, or, you can set it when you save the Product instance, assuming you have a Company instance in mind, since you set null=True, so obviously if company is False, then there is no companyName.
Assuming you have a Company instance already when you save the Product model you can do:
class Product(models.Model):
company = models.ForeignKey(Company, on_delete=models.CASCADE, null=True)
companyName = # I want the name here
_id = models.AutoField(primary_key=True, editable=False)
def save(self, *args, **kwargs):
if self.company:
self.companyName = self.company.name
super(Product, self).save(*args, **kwargs)
def __str__(self):
return self.name
But, the next question is why do you want to even have a field called companyName when you have access to the name field of the Company instance anyway. Try to get it by:
# Get the Product instance you want
product = Product.objects.get(...)
# Then you can get the associated `Company` name like this:
print(product.company.name)
Suggestion
Lately I've been seeing many questions with something like:
_id = models.AutoField(primary_key=True, editable=False)
Not sure why, since Django does that automatically.

How get information from three different tables at once?

I have following models:
class Device(models.Model):
name = models.CharField(max_length=100, blank=False)
description = models.TextField(max_length=500, blank=True)
ip_address = models.GenericIPAddressField(blank=True, null=True)
contact_person = models.ForeignKey(User, on_delete=models.SET_NULL, null=True)
team = models.ForeignKey(Team, on_delete=models.SET_NULL, null=True)
category = models.ForeignKey(Category, on_delete=models.SET_NULL, null=True)
def __str__(self):
return self.name
class TimeSlot(models.Model):
name = models.CharField(max_length=20)
start_slot = models.CharField(max_length=10)
end_slot = models.CharField(max_length=10)
def __str__(self):
return self.name
class Reservation(models.Model):
device = models.ForeignKey(Device, on_delete=models.CASCADE)
time_slot = models.ForeignKey(TimeSlot, on_delete=models.CASCADE)
date_of_reservation = models.DateField()
user = models.ForeignKey(User, on_delete=models.CASCADE)
def __str__(self):
return "{} - {} for device: {} by {}.".format(self.time_slot, self.date_of_reservation, self.device, self.user)
class ForbiddenSlot(models.Model):
device = models.ForeignKey(Device, on_delete=models.CASCADE)
time_slot = models.ForeignKey(TimeSlot, on_delete=models.CASCADE)
def __str__(self):
return str(self.time_slot)
This is simple reservation system. I have problem to understand how create query for three different tables.
I want get all TimeSlots which are not set in ForbiddenSlot and Reservation for given Device name.
I'm not entirely sure if this will work, but I think it will and is definitely worth a shot.
TimeSlot.objects.filter(
forbiddenslot__isnull=True,
reservation__device__name='Device Name',
)
It's not necessarily the easiest thing for me to wrap my head around, but not only does TimeSlot have access to .forbiddenslot_set, it also can filter by forbiddenslot. The same goes for reservation.
I guess changing the structure of your models will be much better, like deleting the model ForbiddenSlot and replacing it with a flag on the reservation model, then you can select all TimeSlots from the reservation model where the forbidden flag is False, like:
reservations = Reservation.objects.only('time_slot').filter(device__name=name_of_the_device,forbidden=False) where forbidden is a boolean field.
Using select_related() will pre-populate the appropriate attributes:
Model.objects.select_related()

Django inline formset with manytomany fields

Ive spent a fair bit of time searching on this subject without finding some real up to date answers. I'm trying to create a form that creates a db entry. The basic idea is this:
Many events can have many people
So, the struggle here is that the user needs to create an event where the user can select all the people that attend. Each person that attends though, has certain things that also needs to be tracked per event. See the model below:
models.py
from django.db import models
from django.contrib.auth.models import User[]
class PersonRole(models.Model):
role = models.CharField(max_length=20, choices=ROLE_CHOICES, unique=True)
# this function will be invoked when this model object is foreign key of other model(for example Employee model.).
def __str__(self):
return self.role
class PersonClass(models.Model):
name = models.CharField(max_length=100, choices=CLASS_CHOICES, unique=True)
color = models.CharField(max_length=6, choices=COLOR_CHOICES, unique=True)
# this function will be invoked when this model object is foreign key of other model(for example Employee model.).
def __str__(self):
return self.name
class Person(models.Model):
name = models.CharField(max_length=100, unique=True)
personclass = models.ForeignKey(PersonClass, on_delete=models.CASCADE, blank=True, null=True)
personrole = models.ForeignKey(PersonRole, on_delete=models.CASCADE, blank=True, null=True)
value = models.IntegerField(default=0)
reliability = models.IntegerField(default=0)
last_item = models.DateField(auto_now=False, blank=True, null=True)
last_event_attended = models.DateField(auto_now=False, blank=True, null=True)
last_manager_attended = models.DateField(auto_now=False, blank=True, null=True)
item_received = models.BooleanField(default=False)
note = models.TextField(null=True, blank=True)
core_attendee = models.BooleanField(default=False)
enabled = models.BooleanField(default=True)
# this function will be invoked when this model object is foreign key of other model(for example Employee model.).
def __str__(self):
return self.name
class Location(models.Model):
name = models.CharField(max_length=100, unique=True)
# this function will be invoked when this model object is foreign key of other model(for example Employee model.).
def __str__(self):
return self.name
class Boss(models.Model):
name = models.CharField(max_length=100, unique=True)
location = models.ForeignKey(Location, on_delete=models.CASCADE)
# this function will be invoked when this model object is foreign key of other model(for example Employee model.).
def __str__(self):
return self.name
class Raid(models.Model):
date = models.DateTimeField(auto_now_add=True)
boss = models.ForeignKey(Boss, on_delete=models.CASCADE, null=True, blank=True)
success = models.BooleanField()
attendees = models.ManyToManyField(Person)
created_by = models.ForeignKey(User,
related_name="raids", blank=True, null=True,
on_delete=models.SET_NULL)
# this function will be invoked when this model object is foreign key of other model(for example Employee model.).
def __str__(self):
return str(self.date)
I've started down the path of just trying to use the generic in-built create\update\delete views and ran into this:
ValueError: 'roster.Person' has no ForeignKey to 'roster.Raid'.
forms.py
class RaidGenericCreateModelForm(forms.ModelForm):
class Meta:
model = Person
exclude = ()
RaidPersonFormSet = inlineformset_factory(Raid, Person, fields=['name', 'personclass', 'personrole', 'item_received'], extra=1, can_delete=False)
views.py
class RaidCreate(CreateView):
model = Raid
template_name = 'roster/raid_create.html'
form_class = RaidGenericCreateModelForm
success_url = None
def get(self, request, *args, **kwargs):
self.object = None
form_class = self.get_form_class()
form = self.get_form(form_class)
person_form = RaidPersonFormSet
return self.render_to_response(
self.get_context_data(form=form,
person_form=person_form
)
)
There are 9-year old posts that say you cannot use inlineformset_factory with many to many fields. So my question here is, what are my options? What is the best way to go about simply creating an Event (referred to as Raid in the model) and at the same time selecting the people from the roster (referred to as Person in the model) and changing the options those people have associated to them for that event?
As an example of what I am trying to accomplish here:
Event 1
-Person A (selected, item_received=True)
-Person B (selected, item_received=False)
-Person C (selected, item_received=False)
-Person D (not selected, item_received=False)
Event 2
-Person A (selected, item_received=False)
-Person B (not selected, item_received=False)
-Person C (selected, item_received=True)
-Person D (selected, item_received=False)
Where the list of persons is showing all persons and some of the persons fields from the Person model.
The alternate thing you can do is use DjangoRestFramework for this purpose.
Using rest you can first send persons data to frontend then in frontend you can create Event and add person details for each event,and in last post all that data using javascript.Try it,it will surely work.

How take modal as data type for field of another modal in Django?

Here I have Seller modal which contains the contact field. I created a new model name as Contact which has fields contact_number and address.
I can simply give a foreign key to the contact field of Seller model to Contact model.
But here I want to use the Contact model as a new data type for the contact field of Seller model.
class Contact(models.Model):
contact_number = PhoneNumberField(blank=False, null=False)
address = models.TextField(blank=False, null=False)
def __str__(self):
return "%s" % self.name
class Seller(models.Model):
company_name = models.CharField(max_length=300, blank=False, null=False)
company_profile = models.TextField(blank=False, null=False)
contact = Contact() #Here I want use Contact model as data type for the contact field
def __str__(self):
return "%s" % self.company_name
Is this possible?
If yes Can anyone please Guide me for that. I am New in Django, I only have basic knowledge of Django.
Here I am using PostgreSQL as a database.
what ever database your are using django will take care of that, follow the documentation for changes in settings if your are using different database instead of sqllite.
class Contact(models.Model):
contact_number = PhoneNumberField(blank=False, null=False)
address = models.TextField(blank=False, null=False)
def __str__(self):
return "%s" % self.name
class Seller(models.Model):
company_name = models.CharField(max_length=300, blank=False, null=False)
company_profile = models.TextField(blank=False, null=False)
contact = models.Foreignkey(Contact,on_delete=models.CASCADE)
def __str__(self):
return "%s" % self.company_name
once go through documentation of foreignkey and models for more info #https://docs.djangoproject.com/en/2.1/topics/db/examples/many_to_one/

Django Model design for a basic inventory application

I am new to Django (and databases for that matter) and trying to create a simple inventory application to help learn. I've been through the tutorials and am going through some books, but I am stuck at what i think is simple, just not sure where to look or how to ask.
With an inventory application, you have your equipment which then has a manufacturer, which the equipment has a model number that only that manufacturer has. Lets say Dell Optiplex 3040. I am also using the admin console right now as well. So i would like to be able to relate equipment to a manufacturer and then also relate the equipment to the model number. It almost seems as I am needing to use the many to many field and the through field to accomplish what I am trying to do but I dont think that is the right way to do it (shown in the link below). https://docs.djangoproject.com/en/1.9/topics/db/models/#many-to-many-relationships
Below is the code I have so far. Thank you.
from django.db import models
# Create your models here.
class Department(models.Model):
department = models.CharField(max_length=50)
def __str__(self):
return self.department
class Manufacturer(models.Model):
manufacturer = models.CharField(max_length=50)
def __str__(self):
return self.manufacturer
class EquipmentModel(models.Model):
equipmentModel = models.CharField(max_length=50)
def __str__(self):
return self.equipmentModel
class Employees(models.Model):
employee_name_first = models.CharField(max_length=25)
employee_name_last = models.CharField(max_length=25)
employee_username = models.CharField(max_length=20)
phone = models.IntegerField()
assigned_equipment = models.ForeignKey('Device', default='undefined')
department = models.ForeignKey('Department', on_delete=models.CASCADE, default='undefined')
job_title = models.ManyToManyField('Job_Positions', default='undefined')
def __str__(self):
return self.employee_username
class Device(models.Model):
ip = models.GenericIPAddressField(protocol='IPv4',unpack_ipv4=False,null=True, blank=True)#might be good to seperate IP in its own class because a device can have multiple IP's
department = models.ForeignKey('Department', on_delete=models.CASCADE)
manufacturer = models.ForeignKey('Manufacturer', on_delete=models.CASCADE)
serial_number = models.CharField(max_length=50)
date_created = models.DateTimeField(auto_now=False, auto_now_add=True)
date_updated = models.DateTimeField(auto_now=True, auto_now_add=False)
comments = models.TextField(blank=True)
def __str__(self):
return self.serial_number
class Job_Positions(models.Model):
position_title = models.CharField(max_length=50)
position_description = models.TextField(blank=True)
def __str__(self):
return position_title
***Edit to add the updated code and the admin.py code in response question I had to answer.
#admin.py
from django.contrib import admin
# Register your models here.
from .models import Device,Department,Manufacturer,Employees, Job_Positions, EquipmentModel
class DeviceModelAdmin(admin.ModelAdmin):
list_display = ["ip", "department","model","serial_number","date_updated"]
list_filter = ["department","model","ip"]
search_fields = ["ip"]
class Meta:
model = Device
class EmployeesModelAdmin(admin.ModelAdmin):
list_display = ["employee_name_first", "employee_name_last", "employee_username", "phone"]
list_filter = ["department"]
class Meta:
model = Employees
admin.site.register(Device, DeviceModelAdmin)
admin.site.register(Department)
admin.site.register(Manufacturer)
admin.site.register(EquipmentModel)
admin.site.register(Employees, EmployeesModelAdmin)
admin.site.register(Job_Positions)
updated models.py
from django.db import models
# Create your models here.
class Department(models.Model):
department = models.CharField(max_length=50)
def __str__(self):
return self.department
class Manufacturer(models.Model):
manufacturer = models.CharField(max_length=50)
def __str__(self):
return self.manufacturer
class EquipmentModel(models.Model):
model_number = models.CharField(max_length=50)
manufacturer = models.ForeignKey('Manufacturer', on_delete=models.CASCADE)
def __str__(self):
return self.model_number
class Employees(models.Model):
employee_name_first = models.CharField(max_length=25)
employee_name_last = models.CharField(max_length=25)
employee_username = models.CharField(max_length=20)
phone = models.IntegerField()
assigned_equipment = models.ForeignKey('Device', default='undefined')
department = models.ForeignKey('Department', on_delete=models.CASCADE, default='undefined')
job_title = models.ManyToManyField('Job_Positions', default='undefined')
def __str__(self):
return self.employee_username
class Device(models.Model):
ip = models.GenericIPAddressField(protocol='IPv4',unpack_ipv4=False,null=True, blank=True)#might be good to seperate IP in its own class because a device can have multiple IP's
department = models.ForeignKey('Department', on_delete=models.CASCADE)
model = models.ForeignKey('EquipmentModel', on_delete=models.CASCADE,null=True)
serial_number = models.CharField(max_length=50)
date_created = models.DateTimeField(auto_now=False, auto_now_add=True)
date_updated = models.DateTimeField(auto_now=True, auto_now_add=False)
comments = models.TextField(blank=True)
def __str__(self):
return self.serial_number
class Job_Positions(models.Model):
position_title = models.CharField(max_length=50)
position_description = models.TextField(blank=True)
def __str__(self):
return position_title
A many-to-many relationship is not what you want here, because any piece of equipment (I assume) can only have one manufacturer.
You do need an intermediate model which stores the model information, and you already have one in your EquipmentModel. I would suggest modifying it as follows:
class EquipmentModel(models.Model):
# This stores information about a particular model of device
manufacturer = models.ForeignKey('Manufacturer', on_delete=models.CASCADE)
model_number = models.CharField(max_length=50)
And then instead of having a foreign key to the manufacturer in Device, replace it with a foreign key to the equipment model:
class Device(models.Model):
# ...
model = models.ForeignKey('EquipmentModel', on_delete=models.CASCADE)