Django - storing logical tests as records - python

I'm working on a Gran Turismo 5 Django application. Here's a very simplified data model:
class Event(models.Model):
name = models.CharField(max_length=256, unique=True)
class EventCriteria(models.Model):
name = models.CharField(max_length=256, unique=True)
events = models.ManyToManyField(Event)
test = ???
class Country(models.Model):
name = models.CharField(max_length=256, unique=True)
class Make(models.Model):
name = models.CharField(max_length=256, unique=True)
country = models.ForeignKey(Country)
class Car(models.Model):
name = models.CharField(max_length=256, unique=True)
make = models.ForeignKey(Make)
class Setup(models.Model):
name = models.CharField(max_length=256, unique=True)
car = models.ForeignKey(Car)
horsepower = models.IntegerField()
For example, a given event might have the criteria 'Country = Italy'. When applied against the model above, that would require a test like the following:
setup.car.make.country.name == u'Italy'
Does anyone have a good framework for how I might structure the EventCriteria model (especially the 'test' field or fields') to make a) storing these tests and b) applying them as filters in future views possible?
Thanks,
Mike

It's not clear on why your "test" isn't a simple boolean field. The question is confusing.
I'm assuming that really want a persistent filter, since that's often requested.
A Django filter is a dictionary.
SomeModel.objects.filter( column=value, column__contains=value )
SomeModel.objects.filter( **{'column':value, 'column__contains':value} )
You can do this to persist your "test".
Convert your "filter" expression to a dictionary.
JSON-encode the dictionary as a BLOB
Save it.
You can apply your test as follows.
Get the filter BLOB
JSON-decode the dictionary
Use the dictionary in a filter for the appropriate class.

Related

Django collection of instances of same model

I'm new to Django
I'm currently using django 3.2.6. I want make multiple instances of route_stop model and store in SchoolRouteStop.route_graph model.I don't want use ForeignKey because i want to make somthing like like nested dict.
from django.db import models
class geo_fence(models.Model):
radius = models.FloatField()
class geo_location(models.Model):
latitude = models.FloatField()
longitude = models.FloatField()
class address(models.Model):
entity = models.fields.CharField(max_length=100)
apt_plot = models.fields.CharField(max_length=100)
street = models.fields.CharField(max_length=100)
city = models.fields.CharField(max_length=100)
state = models.fields.CharField(max_length=2) #state name in short code
zip_code = models.fields.IntegerField()
class route_stop(models.Model): # this for multiple bus stops
route_stop_id = models.fields.IntegerField()
school_id = models.fields.CharField(max_length=100)
route_number = models.fields.CharField(max_length=100)
school_route_stop_uuid = models.fields.CharField(max_length=100, primary_key=True)
registered_arrival_time = models.TimeField()
time_from_src = models.FloatField()
is_school = models.BooleanField(default=False)
geo_fence = models.ForeignKey(geo_fence, on_delete =models.CASCADE)
geo_location = models.ForeignKey(geo_location, on_delete = models.CASCADE)
address = models.ForeignKey(address, on_delete = models.CASCADE)
class SchoolRouteStop(models.Model):
school_id = models.CharField(max_length=100)
school_route_number = models.IntegerField()
route_type = models.CharField(max_length=2)
route_id = str(school_id)+'_'+str(school_route_number)+str(route_type)
route_graph= models.ForeignKey(route_stop,related_name='School', on_delete = models.CASCADE)
# Create your models here.
You have to use a ForeignKey here because you will lose all the Django ORM features and performances if you try to hack this.
Trying to use a JSONField or something else instead would also mean losing integrity constraints you would need to implement yourself, which you really want to avoid.
The way Django works is you implement your models to be stored efficiently in the database, then you use views & serializers to manipulate them.
Your models need to be refined, I really have a hard time understanding their real purpose because there are id fields everywhere (that should also probably be ForeignkeyField), and everything seems a little confusing.
For example, why is school_route_stop_uuid a CharField when UUIDField does exist?
Why is route_id not a property?
Also, make sure to follow the naming conventions in Python, it will make you code way cleaner. According to PEP 8 (https://www.python.org/dev/peps/pep-0008/#class-names):
Class names should normally use the CapWords convention.

django model reference to own attribute

When i create a Django model i want to set the primary_key/ID to a combination of 2 attributes of this Model.
Example model:
class Example(models.Model):
name = models.CharField(max_length=100)
date = models.DateTimeField(default=now)
id = models.CharField(max_length=100, default="{}-{}".format(name, date) primary_key=True)
But he is saving the Model and not the values:
field=models.CharField(default='<django.db.models.fields.related.ForeignKey>-<django.db.models.fields.DateTimeField>', max_length=100, primary_key=True, serialize=False),
I know that name and date are a model in this context, but "self." is not working and i can't find a Django function to get the actual values instead.
It should work like this:
Input:
testmodel = Example(name="foo", date=datetime.now())
testmodel.save()
testmodel-id should look something like this "foo-2020-12-11..."
I don't think you can do that. Because these values are initialized at the making of an object. What you can do is to make your own class method to initialize these values.
class Example(models.Model):
name = models.CharField(max_length=100)
date = models.DateTimeField(default=now)
id = models.CharField(max_length=100, primary_key=True)
# In User class declaration
#classmethod
def create(cls,name, date):
return cls(name=name, date=date, id="{}-{}".format(name,date))
And Use it like this outside the class
p = Example.create("Fred", "11-12-2020")

Not sure I understand dependancy between 2 django models

I am struggling to understand django models relationship.
I have this arborescence:
A train have cars, and those cars are divided into parts. Then those parts all contains different references.
Like, for exemple, all the trains have the 6 cars, and the cars 6 parts. Each part have x reference to be associated.
I would like to use all of them in a template later on, where the user can select the train, the car and the part he worked on, then generate a table from his selections with only the references associated to the parts he selected.
It should update the train and the car (I'm trying to update a stock of elements for a company)
I dont really understand which model field give to each of them. After checking the doc, Ive done something like this but i am not convinced:
class Train(Car):
train = models.CharField(max_length=200)
id = models.CharField(primary_key='True', max_length=100)
selected = models.BooleanField()
class Meta:
abstract = True
class Car(Part):
car = models.CharField(max_length=200)
id = models.CharField(primary_key='True', max_length=100)
selected = models.BooleanField()
class Meta:
abstract = True
class Part(Reference):
part = models.CharField(max_length=200)
id = models.CharField(primary_key='True', max_length=100)
selected = models.BooleanField()
class Meta:
abstract = True
class Reference(models.Model):
reference = models.CharField(max_length=200)
id = models.CharField(primary_key='True', max_length=100)
selected = models.BooleanField()
def __str__(self):
return self.reference
Can someone please help me understand this so I can do well ? Thanks!!
1-)if you add abstract = True in your Model Meta class, your class doesn't created on database as a table. If you store data for any class, you mustn't define abstract = True.
2-)For relations, you can use models.ForeignKey . If you add a class into brackets of another class, it names: inheritance.(You can think like parent-child relation). In database management, we can use foreignkey for one-to-many relationship.
3-)In Django ORM, id field automatically generated. So you don't need to define id field.
If I understand correctly, also you want to store parts of user's selected.
So, your model can be like that:
class Train(models.Model):
name = models.CharField(max_length=200) # I think you want to save name of train
class Car(models.Model):
train = models.ForeignKey(Train,on_delete=models.Cascade)
name = models.CharField(max_length=200)
class Part(models.Model):
car = models.ForeignKey(Car,on_delete=models.Cascade)
name = models.CharField(max_length=200)
class Reference(models.Model):
part = models.ForeignKey(Part,on_delete=models.Cascade)
name = models.CharField(max_length=200)
def __str__(self):
return self.reference
#addtional table for storing user's references
class UserReference(models.Model):
user = models.ForeignKey(User,on_delete=models.Cascade)
reference = models.ForeignKey(Reference,on_delete=models.Cascade)
name = models.CharField(max_length=200)
With this definitions, you can store user's definition on UserReference table. And with Django Orm, you can access train object from UserReferenceObject.
#user_reference: UserReference object like that result of UserReference.objects.first()
user_reference.reference.part.car.train.name

Simplifying this django query - Have django obtain instances based on values

So I currently have this django query. The first two statements are needed in order to obtain the 3rd statement. My question is if there is a way to only use the 3rd statements without using the first two statements.
#patient_name and quest are two strings
patientobj = modelPatient.objects.get(patient_name=patient_name)
questobj = modelInterviewQuestion.objects.get(question=quest)
answer = modelInterviewAnswer.objects.get(patients=patientobj, questions=questobj)
I know I could do something like this
answer = modelInterviewAnswer.objects.get(patients= modelPatient.objects.get(patient_name=patient_name), questions= modelInterviewQuestion.objects.get(question=quest))
but I was wondering if there is anything simpler ?
Here are the relationship between models
class modelPatient(models.Model):
patient_name = models.CharField(max_length=128, unique=False)
patient_sex = models.CharField(max_length=128, unique=False)
patient_image = models.ImageField(upload_to='images/',
class modelInterviewQuestion(models.Model):
question = models.CharField(max_length=1000, unique=True)
class modelInterviewAnswer(models.Model):
patients = models.ForeignKey(modelPatient)
questions = models.ForeignKey(modelInterviewQuestion)
patient_response = models.CharField(max_length=1000, unique=True)
Try out this.
answer = modelInterviewAnswer.objects.get(patients__patient_name=patient_name, questions__question=quest)
Please go through this documentation to know how to write query that span relationship.
I want to draw you attention at naming convention.
Don't prefix model name with model, for example modelPatient should be only Patient.
Don't need to write patient_<field_name> in model. It should be only <field_name>
For example your Paitent model should look like
class Patient(models.Model):
name = models.CharField(max_length=128, unique=False)
sex = models.CharField(max_length=128, unique=False)
image = models.ImageField(upload_to='images/')
Follow same instructions for other models too.
class InterviewQuestion(models.Model):
question = models.CharField(max_length=1000, unique=True)
class InterviewAnswer(models.Model):
patients = models.ForeignKey(modelPatient)
interview_questions = models.ForeignKey(modelInterviewQuestion)
patient_response = models.CharField(max_length=1000, unique=True)
So Your query will be.
answer = InterviewAnswer.objects.get(patients__name=patient_name, interview_questions__question=quest)

How to create django database model that "knows" what kind of category it is?

In Django, I have the following models.py
class Product(RandomPrimaryIdModel):
title = models.CharField(max_length=20, blank=True, null=True)
price = models.CharField(max_length=20, blank=True, null=True)
condition = models.CharField(max_length=20, blank=True, null=True)
class Mattress(Product):
length = models.CharField(max_length=50)
size = models.CharField(max_length=5)
class Pillow(Product):
shape= models.CharField(max_length=50)
comfort= models.CharField(max_length=5)
The idea is that there's a "product" model and several "product_type" models. I'm trying to create a database scheme that relates the two. The end goal is so that when I given access to a primary id for an object whose product_type is unknown, I can simply query/filter that object to find out what the product_type is of the object.
I know that sounds a bit confusing, but how would I go about implementing the correct way? The current scheme (the one above) is not the correct solution I believe.
According to the docs on multi-table inheritance you can reference the lowercase name of the model. In your case to find out the "product type" you'd do something like:
product = Product.objects.get(id=12)
try:
mattress = product.mattress
is_mattress = True
except Mattress.DoesNotExist:
is_mattress = False
You could abstract this out to a helper method that would do the tests for you and return the type as a string or enum of some sort.
If you have a reference to an object, can't you use something like:
p = Product.objects.get(id=1)
class_of_p = str(p.__class__)
and then parse the resulting string
"<class 'whatever.models.Pillow'>"
to find what you need? Apologies if I'm missing something.

Categories