How To Implement Dynamic Columns in Django models based on POST request - django

I have created a Django RestFramework with few models like Offers, Dailysubs and Requisitions to which I need add columns dynamically for a POST request.
There should be 1-10 blank columns for a model and a Master table which has fields to configure the new column like name and other properties.
I also need to implement an approach to add these dynamic columns into serializers.
class Requisition(models.Model):
skill = models.CharField(max_length=255)
superClass = models.CharField(max_length=255)
jobFamily = models.CharField(max_length=255)
yearOfExp = models.CharField(max_length=255)
grade = models.CharField(max_length=100)
...
...
class Offer(models.Model):
businessGroup = models.CharField(max_length=100)
status = models.CharField(max_length=20)
sNo = models.IntegerField()
recruiter = models.CharField(max_length=100)
manager = models.CharField(max_length=100)
dateOfOffer = models.DateField()
dateOfJoining = models.DateField()
...
...
class MasterTable(models.Model):
columnName = models.CharField(max_length=100)
tableName = models.CharField(max_length=100)
columnFieldType = models.CharField(max_length=100)
I read another post related to this at Django Models (dynamic?) but I don't know if I should create another model to hold these blank columns or if I should add blank columns to each model.

Related

Merge Django models into a view

I am attempting to merge and pull data from three Django models into a view. Players and Events relate to each other in the Details model (a player can attend many events) using models.ForeignKey.
In other platforms I would have written a DB View to join tables and the application would query that view.
From what I understand Django does not support data views within Models.
Looking for help on how I would approach this in Django.
class Players(models.Model):
firstName = models.CharField(max_length=255)
lastName = models.CharField(max_length=255)
highSchool = models.CharField(max_length=255)
gradYear = models.IntegerField()
slug = models.SlugField(default="", null=False)
class Events(models.Model):
title = models.CharField(max_length=255)
location = models.CharField(max_length=255)
date = models.DateField()
class Details(models.Model):
event = models.ForeignKey(Events, on_delete=models.CASCADE)
player = models.ForeignKey(Players, on_delete=models.CASCADE)
height = models.IntegerField(default=None, blank=True)
weight = models.IntegerField(default=None, blank=True)
def playerdetail(request,slug):
playerinfo = Details.objects.get(id=1)
template = loader.get_template('playerdetail.html')
context = {
'playerinfo': playerinfo,
}
return HttpResponse(template.render(context, request))
You are actually doing what you needed to do with the code you provided.
When you are invoking a query on a model that connects those two entities (Players,Events), it performs the join when you try to access each of these properties through the foreign key fields.
For example, for accessing the player information (which makes the Django ORM perform the join operation in the background):
# Get the first name of the player
first_name = playerinfo.player.firstName
For filtering and showing in other places, you can use the notation field__subfield
For more information, please read the examples of this website:
https://books.agiliq.com/projects/django-orm-cookbook/en/latest/index.html

Django add a field to a model based on another model

I have a model for a product:
class Product(models.Model):
name = models.CharField(verbose_name=_("Name"), max_length=120)
slug = AutoSlugField(populate_from="name", verbose_name=_("Slug"), always_update=False, unique=True)
I want to have a separate model ProductFields:
class ProductFields(models.Model):
field_name = models.CharField()
field_type = models.CharField()
field_verbose_name = models.CharField()
field_max_length = models.IntegerField()
filed_null = models.CharField()
field_blank = models.BooleanField()
field_default = models.CharField()
...
So the idea is whenever I add new ProductField I want Product model to migrate that added field to its database.
For Example:
ProductFields.objects.create(field_name='description', field_type='CharField', field_verbose_name='Description', field_max_length=255, filed_null=True, filed_blank=True)
This should transform Product modal to:
class Product(models.Model):
name = models.CharField(verbose_name=_("Name"), max_length=120)
slug = AutoSlugField(populate_from="name", verbose_name=_("Slug"), always_update=False, unique=True)
description = models.CharField(verbose_name="Description", max_length= 255, null=True, blank=True)
Please let me know if you have any idea how this can be done?
If you're looking for a way to create a dynamic model you can look into these suggestions.
HStoreField using django-hstore : https://django-hstore.readthedocs.io/en/latest/
JSONField: JSONField is similar to HStoreField, and may perform better with large dictionaries. It also supports types other than strings, such as integers, booleans and nested dictionaries.https://django-pgfields.readthedocs.io/en/latest/fields.html#json-field
Or you can use a NoSQL database (Django MangoDB or another adaptation)

How to change field value dynamically depended on dropdown selection in django

I've been searching Google, but couldn't find a simple answer to this problem:
I have a django models that stores students information and three other models like this:
class Level(models.Model):
name = models.CharField(max_length=50)
class Pricing(models.Model):
level = models.ForeignKey(Level, on_delete=models.PROTECT)
price = models.PositiveSmallIntegerField(default=0)
class Enrollment(models.Model):
student = models.ForeignKey(Student, on_delete=models.PROTECT)
level = models.ForeignKey(Level, on_delete=models.CASCADE)
date_enrolled = models.DateField()
price = models.PositiveSmallIntegerField(default=0)
I want the Enrollment.price field to be populated dynamically depending on Enrollment.level field value. In javascript, it amounts to setting an event listener to Enrollement.level, but I can't find the equivalent in django.
hi you can modify your save method to fill automatically field price from Level model
Enrollment.level
class Enrollment(models.Model):
student = models.ForeignKey(Student, on_delete=models.PROTECT)
level = models.ForeignKey(Level, on_delete=models.CASCADE)
date_enrolled = models.DateField()
price = models.PositiveSmallIntegerField()
def save(self,*args,**kwargs):
self.price = Pricing.objects.get(level=self.level).price
super().save(*args,*kwargs)
but I recommend to rewrite your model like above example because its simple and you can access to price of every level directly
like Enrollment.level.price
class Level(models.Model):
level = models.CharField(max_length=50,unique=True)
price = models.PositiveSmallIntegerField(default=0)
class Enrollment(models.Model):
student = models.ForeignKey(Student, on_delete=models.PROTECT)
level = models.ForeignKey(Level, on_delete=models.CASCADE)
date_enrolled = models.DateField()
I hope it helped you

Django tables connection

I have 3 django tables connected like this:
Is there anyway to make a query for table Table that will get id_equip from table equip?
models.py
class Vendor(models.Model):
vendor_name = models.CharField(max_length=50)
def __str__(self):
return self.vendor_name
class Equipment(models.Model):
equipment_name = models.CharField(max_length=50)
id_vendor = models.ForeignKey(Vendor, on_delete=models.CASCADE, default=None)
def __str__(self):
return self.equipment_name
class Table(models.Model):
table_name = models.CharField(max_length=100)
id_vend = models.ForeignKey(Vendor, on_delete=models.CASCADE, default=None)
id_equip = models.ManyToManyField(Equipment)
This part of the django docs is relevant and helpful, I definitely recommend your review at least that section and ideally the whole page.
Your models are already denormalized as evidenced by Table.id_equip which relates to Equipment so you could do:
table = Table.objects.get(SOME_FILTER)
equipment_ids = list(table.id_equip.all().values_list('id', flat=True))
If you wanted to go through the vendor I'd suggest:
table = Table.objects.get(SOME_FILTER)
equipment_ids = list(Equipment.objects.filter(vendor_set__table_set=table).values_list('id', flat=True))
I would recommend that you don't name your relationship fields with id_. With an ORM, these fields should represent the instances of the Model they are mapping to. For example:
class Table(models.Model):
name = models.CharField(max_length=100)
vendor = models.ForeignKey(Vendor, on_delete=models.CASCADE, default=None)
equipment = models.ManyToManyField(Equipment)
If you're trying to create the model on top of an existing table, you can make use of the db_column parameter when defining the field.
vendor = models.ForeignKey(Vendor, on_delete=models.CASCADE, default=None, db_column="id_vend")

Django - query the records in all tables that have the foreign key equal to the selected record in the main table

In Django I want to query the records in all tables that have the foreign key project = ProjectMain's chosen pk. So if I choose a record in ProjectMain and it's pk=2 I also want the records from the other three tables where the foreign key product=2.
Tables Methods, Things, and MoreStuff can have multiple records with project=2.
Here are the tables:
class ProjectMain(models.Model):
username = models.ForeignKey(User, on_delete=models.CASCADE)
comment = models.CharField(max_length=60)
product = models.ForeignKey(ProductType, on_delete=models.CASCADE)
filler = models.CharField(max_length=100)
class Methods(models.Model):
method_name = models.CharField(max_length=10)
method_test = models.CharField(max_length=50, null=False)
project = models.ForeignKey(ProjectInformation, on_delete=models.CASCADE)
class Things(models.Model):
thing1 = models.CharField(max_length=10)
thing2 = models.CharField(max_length=50, null=False)
project = models.ForeignKey(ProjectInformation, on_delete=models.CASCADE)
class MoreStuff(models.Model):
stuff1 = models.CharField(max_length=10)
stuff2 = models.CharField(max_length=50, null=False)
project = models.ForeignKey(ProjectInformation, on_delete=models.CASCADE)
I've been trying Django querysets and am getting nowhere. Please help.
You can access them via the related_name property as defined in ForeignKey.
project_main = ProjectMain.objects.get(id=2)
methods = project_main.methods_set.all() # All the Methods related to the instance
things = project_main.things_set.all() # All the Methods related to the instance
more_stuffs = project_main.morestuff_set.all() # All the Methods related to the instance