How to use variables in django models.py, (DEFAULT properties of fields) - python

I would like that, when clicking on one of the companies below, a variable is stored (until the browser is closed) with the company's code.
And, I need this variable to populate the 'CompanyCode' fields as default value.
FOR EXAMPLE:
class Employee(models.Model):
class Meta:
db_table = 'employee'
CompanyCode= models.IntegerField(
null=False,
blank=None,
default = 'VARIABLE',
db_column='CompanyCode'
)
After being stored in the database, I need to make a query to show all tuples where CompanyCode is equal to a certain value.
Could someone tell me a python, django component that I could use to separate the data for each company? I thought of using JavaScript Local Storage at first.

Related

Creating models/database Django FK

I’m a student bachelor ICT and currently making a simple webapp. I have no experience with python and django, so im struggling a bit.
I have a running empty MARIADB in a Linux Kali VM.
I have made a ERD from my web app in visual paradigm. I exported the .dll and created the database in MySQL workbench. I used inspectdb to import the django/python code for my models.py.
So far so good.
Django offers the User module, so i didn’t make an own user class
(auth_user).
The problem is: How do I build the relation with the auth_user class between a class i created called “case”? It’s asking for a default FK value and i have no idea what i means... I googled everywhere, but just “don’t understand”.
“Class case“ i want to set a relation with a user class. Explanation: A user can create one or more Cases.
“Class item”. A case can have or more Items (under investigation).
The error I am receiving when declaring a FK in Class item with Case:
“You are trying to add a non-nullable field 'zaakid' to gegevensdrager without a default; we can't do that (the database needs something to populate existing rows).
Please select a fix:
1) Provide a one-off default now (will be set on all existing rows with a null value for this column)
2) Quit, and let me add a default in models.py“
Default value!? I just want a row in Class Item referring to the Case primairy key ID. I have no clue what the default should be...
Example of the code:
class Case(models.Model):
registratienummer = models.CharField(db_column='Registratienummer', unique=True, max_length=10, validators=[RegexValidator(r'^[0-9]{10}$')])
onderzoeksname = models.CharField(db_column='Onderzoeksnaam', blank=False, max_length=255)
Made_by = models.ForeignKey('AuthUser', db_column='Aangemaakt Door', null=True, on_delete=models.SET_NULL)
class Item(models.Model):
merk = models.CharField(db_column='Merk', max_length=255)
type = models.CharField(db_column='Type', max_length=255, blank=True, null=True)
serienummer = models.CharField(db_column='Serienummer', max_length=255, blank=False)
imei = models.CharField(db_column='IMEI', max_length=15, blank=True, null=True, validators=[RegexValidator(r'^[0-9]{15}$')])
#gegevensdrager_soortsocode = models.ForeignKey('GegevensdragerSoort', models.DO_NOTHING, db_column='Gegevensdrager_SoortSoCode')
#zaakid = models.ForeignKey('Zaak', db_column='Zaak_referentie', on_delete=models.DO_NOTHING)
After that I tried the inspectdb > models.py. This works but I want to add constraints etc, but it doesn’t work for some reason. It’s giving me all kinds of traceback I can’t explain. But first things first, my post is long enough. Hope someone can help me out a bit, since I’m quite stressed out at the moment.
With kind regards,
Florus.
If the database is already populated with data and you add a new field to that data, then Django needs something to assign to the data already in the database. In this case, you had data that didn't already have a foreign key associated with them, so the requested default is what the program should automatically associate with the previous data.
If you remove the data from your database, this should run normally, or you can give it data to populate those Cases with and manually change it later.

Django annotate, combine multiple related values onto same instance

I have a django app with the following models:
class Person(models.Model):
first_name = models.CharField(max_length=100)
last_name = models.CharField(max_length=100)
class Job(models.Model):
title = models.CharField(max_length=100)
class PersonJob(models.Model):
person = models.ForeignKey(Person, related_name='person_jobs')
job = models.ForeignKey(Job, related_name='person_jobs')
is_active = models.BooleanField()
Multiple Person instances can hold the same job at once. I have a Job queryset and am trying to annotate or through some other method attach the names of each person with that job onto each item in the queryset. I want to be able to loop through the queryset and get those names without doing an additional query for each item. The closest I have gotten is the following:
qs = Job.objects.all().annotate(first_names='person_jobs__person__first_name')
.annotate(last_names='person_jobs__person__last_name')
This will store the name on the Job instance as I would like; however, if a job has multiple people in it, the queryset will have multiple copies of the same Job in it, each with the name of one person. Instead, I need there to only ever be one instance of a given Job in the queryset, which holds the names of all people in it. I don't care how the values are combined and stored; a list, delimited char field, or really any other standard data type would be fine.
I'm using Django 2.1 and Postgres 10.3. I would strongly prefer to not use any Postgres specific features.
You can use either ArrayAgg or StringAgg:
from django.contrib.postgres.aggregates import ArrayAgg, StringAgg
Job.objects.all().annotate(first_names=StringAgg('person_jobs__person__first_name', delimiter=',')
Job.objects.all().annotate(people=ArrayAgg('person_jobs__person__first_name'))

Design an observation pattern in Django Rest Framework

I want to implement something like the pattern which introduced in this answer. For example I have four models like this:
class Protperty(models.Model):
property_type = models.CharField(choices=TYPE_CHOICES, default='float', max_length=100)
property_name = models.CharField(max_length=100)
class FloatProperty(models.Model):
property_id = models.ForeignKey(Property, related_name='value')
value = models.FloatField(default=0.0)
class IntProperty(models.Model):
property_id = models.ForeignKey(Property, related_name='value')
value = models.IntField(default=0)
class StringProperty(models.Model):
property_id = models.ForeignKey(Property, related_name='value')
value = models.CharField(max_lenght=100, blank=True, default='')
After defining these classes, I do not know how I must implement serializer or view classes. For example for writing serializer I want to put a field value, which must be set depend of type of object currently is serialized or deserialilzed(property_type defines it).
I am new to django and rest framework too, please give me some suggestions for implementing such models and serializers.
Edit:
In general I want to construct some models that using them I able to store run time defining property with different values and able to query them further. For example I have a store and it has different goods which each one has specific property and I want to query them using a specific property.

How to use unique_together method in django views

class Model1(models.Model):
username = models.CharField(max_length=100,null=False,blank=False,unique=True)
password = models.CharField(max_length=100,null=False,blank=False)
class Model2(models.Model):
name = models.ForeignKey(Model1, null=True)
unique_str = models.CharField(max_length=50,null=False,blank=False,unique=True)
city = models.CharField(max_length=100,null=False,blank=False)
class Meta:
unique_together = (('name', 'unique_str'),)
I've already filled 3 sample username-password in Model1 through django-admin page
In my views I'm getting this list as
userlist = Model1.objects.all()
#print userlist[0].username, userlist[0].password
for user in userlist:
#here I want to get or create model2 object by uniqueness defined in meta class.
#I mean unique_str can belong to multiple user so I'm making name and str together as a unique key but I dont know how to use it here with get_or_create method.
#right now (without using unique_together) I'm doing this (but I dont know if this by default include unique_together functionality )
a,b = Model2.objects.get_or_create(unique_str='f3h6y67')
a.name = user
a.city = "acity"
a.save()
What I think you're saying is that your logical key is a combination of name and unique_together, and that you what to use that as the basis for calls to get_or_create().
First, understand the unique_together creates a database constraint. There's no way to use it, and Django doesn't do anything special with this information.
Also, at this time Django cannot use composite natural primary keys, so your models by default will have an auto-incrementing integer primary key. But you can still use name and unique_str as a key.
Looking at your code, it seems you want to do this:
a, _ = Model2.objects.get_or_create(unique_str='f3h6y67',
name=user.username)
a.city = 'acity'
a.save()
On Django 1.7 you can use update_or_create():
a, _ = Model2.objects.update_or_create(unique_str='f3h6y67',
name=user.username,
defaults={'city': 'acity'})
In either case, the key point is that the keyword arguments to _or_create are used for looking up the object, and defaults is used to provide additional data in the case of a create or update. See the documentation.
In sum, to "use" the unique_together constraint you simply use the two fields together whenever you want to uniquely specify an instance.

Django Mongodb ListField not saving or updating

I am starting to create a webapp using Django and MongoDB. Everything is working fine when I create a model and save it into the Database. Now, I do a "Class.objects.get()" to get the object I need from my DB and I have one field called "media" which is a ListField(). I had tried doing either:
Concert.media.append(list)
or
Concert.media.extend(list)
and then
Concert.save()
This is my "Concert" object in my models.py:
class Concert(models.Model):
main_artist = models.CharField(max_length=50)
concert_id = models.AutoField(primary_key=True)
openers = ListField(EmbeddedModelField('Opener'))
concert_date = models.DateField()
slug = models.SlugField(unique=True)
media = ListField()
And when I go to see the results in does not update the object. No values where saved. If someone can help me I going to give a super cyber fist bump.
Concert is a class, not an instance. You can't save a class. You need to make an instance of the class and save that. Something like
c = Concert()
c.media.append(list)
c.save()
(btw, just as a note, list is a bad variable name because list is a type in python. Never use types as variable names (though everyone is guilty of this at one point or another, including me.))

Categories