how to make dependent dropdown form in django - django

I have three models and every three models are dependent with each other.while adding the Studentfee model through form when I select the student name then the course price should appear only related to that student's course selection
models.py
from django.db import models
from django.db.models import CASCADE
class Course(models.Model):
title = models.CharField(max_length=250)
basic_price = models.CharField(max_length=100)
advanced_price = models.CharField(max_length=100)
basic_duration = models.CharField(max_length=50)
advanced_duration = models.CharField(max_length=50)
def __str__(self):
return self.title
class Student(models.Model):
name = models.CharField(max_length=100)
courses = models.ManyToManyField(Course)
address = models.CharField(max_length=200)
email = models.EmailField()
phone = models.CharField(max_length=15)
image = models.ImageField(upload_to='Students',blank=True)
joined_date = models.DateField()
def __str__(self):
return self.name
class StudentFee(models.Model):
student = models.ForeignKey(Student,on_delete=CASCADE)
total_fee = models.ForeignKey(Course,on_delete=CASCADE) # should dynamically generate in the form based on the selection of student.how ??
first_installment = models.IntegerField(blank=True)
second_installment = models.IntegerField(blank=True)
third_installment = models.IntegerField(blank=True)
remaining = models.IntegerField(blank=True)
def __str__(self):
return self.total_fee

I think you dealing with the problem about what should be computed and what should be stored.
I think you will need another model to manage this, something like
CourseSelection, and cost should be computed at the time of the payment and then stored as CourseSelectionPayment

Related

Django find common instances data in two models

I have models like:
class Hospital(models.Model):
name = models.CharField(max_length=200, unique=True)
manager_name = models.CharField(max_length=200, default='')
manager_id = models.CharField(max_length=200)
def __str__(self):
return f'{self.name}'
class Sick(models.Model):
name = models.CharField(max_length=200, default='')
nationalID = models.CharField(max_length=200)
illName = models.CharField(max_length=200)
hospital = models.ForeignKey(Hospital, related_name='sicks', on_delete=models.DO_NOTHING)
def __str__(self):
return f'({self.name}, {self.nationalID})'
class Employee(models.Model):
name = models.CharField(max_length=200, default='')
nationalID = models.CharField(max_length=200)
company = models.ForeignKey(Company, related_name='employees', on_delete=models.CASCADE)
def __str__(self):
return f'({self.name}, {self.nationalID})'
views:
#api_view(['POST'])
def get_sick_employee_by_hospital(request):
pass
and a serializer like :
from rest_framework import serializers
class NameSerializer(serializers.Serializer):
name = serializers.CharField(required=True, max_length=200, allow_null=False)
my problem is :
my view get_sick_employee_by_hospital() receives a hospital name and it must return all sick peoples that are employees and They have visited that hospital, in a dictionary with keys 1,2,3,..., n and values like "(name, nationalID)".
Pay attention that it does not matter which value is assigned to which key.
What is the best way to do that ? how can i get all sick peoples that are employees and They have visited a hospital?

Query with multiple foreign keys (django)

I'm making a searchbar for a site I'm working on and I'm having trouble when I want to filter different fields from different models (related between them) Here are my models:
class Project(models.Model):
name = models.CharField(max_length=250)
objective = models.CharField(max_length=250)
description = models.TextField()
launching = models.CharField(max_length=100, null=True, blank=True)
image = models.ImageField(
upload_to='imgs/', null=True, blank=True)
image_thumbnail = models.ImageField(
upload_to='thumbnails/', null=True, blank=True)
slug = models.CharField(max_length=250)
class Meta:
db_table = 'project'
def __str__(self):
return self.name
class Institution(models.Model):
name = models.CharField(max_length=250)
project = models.ManyToManyField(Proyecto)
class Meta:
db_table = 'institution'
def __str__(self):
return self.name
And I want to be able to search by the name of the project or the institution, but my code only takes the institution's name.
def searchbar(request):
if request.method == 'GET':
search = request.GET.get('search')
post = Project.objects.all().filter(name__icontains=search, institution__name__icontains=search)
return render(request, 'searchbar.html', {'post': post, 'search': search})
How can I search for all the projects that match by its name OR the institution's name?
BTW, I'm using SQL, not sure if it's relevant, but I thought I should add that info.
You can .filter(…) [Django-doc] with Q objects [Django-doc]:
from django.db.models import Q
Project.objects.filter(Q(name__icontains=search) | Q(institution__name__icontains=search))
or you can work with the _connector parameter:
from django.db.models import Q
Project.objects.filter(
name__icontains=search,
institution__name__icontains=search,
_connector=Q.OR
)

Basic data model for a food tracker

I am new to data modeling and trying to develop a Django model for a simple food tracker.
What did you eat?
Pancakes
Meal
Breakfast
Ingredients
Eggs
Flour
Milk
Allergens
Eggs
When the user logged their Food, Meal, and Ingredients it would lookup to see if any of those ingredients are a known allergen. What would be the appropriate data model for this? My guess is below.
from django.db import models
from django.conf import settings
class Meal(models.Model):
name = models.CharField(max_length=50)
def __str__(self):
return self.name
class Food(models.Model):
date = models.DateTimeField()
name = models.CharField(max_length=50)
notes = models.TextField(max_length=200, null=True)
meal = models.ForeignKey(Meal, on_delete=models.CASCADE)
user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE)
def __str__(self):
return self.name
class Ingredient(models.Model):
name = models.CharField(max_length=50)
foods = models.ManyToManyField(Food)
def __str__(self):
return self.name
class Allergen(models.Model):
name = models.CharField(max_length=50)
def __str__(self):
return self.name
ingredients = models.ManyToManyField(Ingredient)
Just add an is_allergent boolean field to Ingrediant model.
Think of allergy as just an attribute of Ingrediant. it could be allergic or not.

Simple Django Model (Add to Cart)

This is my first Django project and I am trying to implement add-to-cart features.
What changes should I make in this model so that multiple "Item" can be added into "Order", and also keep track of item quantity?
from django.db import models
from django.utils import timezone
# Create your models here.
class Order(models.Model):
customer = models.ForeignKey('Customer')
ordered_item = models.ForeignKey('OrderQuantity', on_delete=models.CASCADE, null=True)
address = models.TextField()
created_date = models.DateTimeField(default=timezone.now)
class Customer(models.Model):
first_name = models.CharField(max_length=50)
last_name = models.CharField(max_length=50)
email = models.EmailField()
phone = models.CharField(max_length=50)
def __str__(self):
return self.first_name
class Item(models.Model):
name = models.CharField(max_length=50)
price = models.DecimalField(default=0.00, max_digits=100, decimal_places=2)
description = models.TextField(null=True)
summary = models.TextField(null=True)
type = models.CharField(max_length=50, null=True)
brand = models.CharField(max_length=50, null=True)
weight = models.DecimalField(default=0.00, max_digits=100, decimal_places=3)
picture = models.ImageField(null=True, upload_to='images/')
created_date = models.DateTimeField(default=timezone.now)
def __str__(self):
return self.name
class OrderQuantity(models.Model):
product = models.ForeignKey('Item')
quantity = models.PositiveIntegerField()
You need to create ManyToManyField in Order Model
class Order(models.Model):
customer = models.ForeignKey('Customer')
ordered_item = models.ForeignKey('OrderQuantity', on_delete=models.CASCADE, null=True)
address = models.TextField()
created_date = models.DateTimeField(default=timezone.now)
items = models.ManyToManyField(Item)
Then you can add items to order in this way:
someorder.items.add(someItem)
Use ManyToManyField in your Item Model
class Item(models.Model):
orders = models.ManyToManyField(Order)
---
So one item have many orders. You can access it by order.item_set or item.orders
It depends on what your Item model is.
If Item is contains a type of product - you may want to use many-to-many field in your Order model, like so:
class Order(models.Model):
...
items = models.ManyToManyField(Item)
...
If Item describes one real item (not type of items), the proper way would be using ForeignKey in your Item model:
class Item(models.Model):
...
order = models.ForeignKey(Order)
...

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)