How can I get the field pto from emplyees app and use it in the permission app.
employee/models.py
class Employee(AbstractUser):
department = models.ForeignKey(Department, on_delete=models.CASCADE,blank=True, null=True)
pto = models.IntegerField(default=20)
is_deleted = models.BooleanField(default=False)
is_superuser = models.BooleanField(default=False)
roles = models.ManyToManyField(Role, related_name='+')
def __str__(self):
return self.username
permission/models.py
class Permission(models.Model):
STATUS = (
('PENDING', 'PENDING'),
('DENIED', 'DENIED'),
('ACCEPTED', 'ACCEPTED')
)
user = models.ForeignKey(Employee, on_delete=models.CASCADE, related_name='lorem')
description = models.CharField(max_length=255)
date_created = models.DateTimeField(auto_now=True, blank=True, null=True)
date = models.DateField()
status = models.CharField(max_length=200, choices=STATUS, default=STATUS[0][0])
is_deleted = models.BooleanField(default=False)
def __str__(self):
return self.description
sorry if a was not clear, thanks in advance
add this to class Permissions model
from yourproject.apps.employee.models import Employee
class Permission(models.Model):
..........
def get_pto(self):
return int(self.user.pto) # if it's floating point number then change int to float
now you can use get_pto in your html, {{ form.get_pto }}
Sorry if this is not what you are looking for, let me know clearly and I will try to answer if I can.
Related
I'm trying to save unique name in the database but the problem I can save the same with different letters, for example I can save (IT, it, iT, It) I don't want to save it like that.
Model:
class Service(models.Model):
id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
name = models.CharField(max_length=127, unique=True, null=False, blank=False) # that field
is_active = models.BooleanField(default=True)
is_deleted = models.BooleanField(default=False)
created_at = models.DateTimeField(auto_now_add=True)
created_by = models.ForeignKey(
"accounts.User",
on_delete=SET_NULL,
blank=False,
null=True,
related_name="service_created_by",
)
def __str__(self):
return f"{self.name}"
A very simple solution:
class Service(models.Model):
name = models.CharField(max_length=50, unique=True)
....
def clean(self):
self.name = self.name.capitalize()
this one helped me
class Service(models.Model):
name = models.CharField(max_length=50, unique=True, null=False, blank=False)
....
class Meta:
constraints = [
models.UniqueConstraint(Lower("name"), name="unique_name"),
]
def clean(self):
self.name = self.name.capitalize()
it only happens when I create new chatroom with the same admin
this is what I wrote in my models.py
class ChatRoom(models.Model):
id = models.UUIDField(primary_key=True, unique=True,
default=uuid.uuid4, editable=False)
name = models.CharField(max_length=100, null=False, blank=True)
users = models.ManyToManyField(User, through='Membership')
admin = models.ForeignKey(
User, null=False, blank=False, on_delete=models.CASCADE, related_name='admin')
date_created = models.DateTimeField(auto_now=True)
def __str__(self):
return self.name
class Membership(models.Model):
id = models.UUIDField(primary_key=True, unique=True,
default=uuid.uuid4, editable=False)
user = models.ForeignKey(User, on_delete=models.CASCADE)
chatroom = models.ForeignKey(ChatRoom, on_delete=models.CASCADE)
date_joined = models.DateTimeField(auto_now=True, null=False, blank=False)
def __str__(self):
return self.user
class Meta:
unique_together = [['user', 'chatroom']]
when i write this in the shell:
from .main.models import ChatRoom,Membership
from django.contrib.auth.models import User
user = User.objects.get(username = 'someone')
chatroom = ChatRoom(admin = user, name = 'something')
chatroom.save()
chatroom2 = ChatRoom(admin = user, name = 'somethingElse')
chatroom2.save()
after i save chatroom2 i get this error : django.db.utils.IntegrityError: UNIQUE constraint failed: main_chatroom.admin_id
can anyone help me?
so it turned out that i did something that made all migrations does not have any affect on the database
so i created new project and copied all my code to the new project( yes i know this is not the right way to do things but it was the easiest way for me) and everything now works great
I have a models looks like this
class Transaction(models.Model):
user = models.ForeignKey(User, on_delete=models.CASCADE, null=True, blank=True)
income_period_choices = (("Weekly", "Weekly"), ("Fortnightly", "Fortnightly"))
chp_reference = models.CharField(max_length=50, unique=True)
rent_effective_date = models.DateField(null=True, blank=True)
class FamilyGroup(models.Model):
name = models.CharField(max_length=10, choices=name_choices)
transaction = models.ForeignKey(
Transaction, on_delete=models.CASCADE, related_name="family_groups"
)
family_type = models.ForeignKey(
FamilySituation, on_delete=models.PROTECT, null=True, blank=True
)
last_rent = models.DecimalField(
help_text="per week", max_digits=7, decimal_places=2, null=True, blank=True
)
#property
def rent_assessment_rate(self):
return RentAssessmentRate.objects.get(active="Yes") # here i think i should add select_related maybe or something, but im not sure
#property
def ftb_rate(self):
return self.rent_assessment_rate.ftb
#property
def cra_rate(self):
return self.rent_assessment_rate.cra
#property
def maintenance_rate(self):
return self.rent_assessment_rate.maintenance
views
def index(request):
transaction = Transaction.objects.all().prefetch_related('family_groups')
return render(request, 'cra/index.html', {"transaction":transaction})
So I'm getting a duplicated queries from RentAssessmentRate table while trying to retrieve the data on the FamilyGroup table.
What would be a good approach to avoid such duplicates? Thanks in advance
Apologies if this question is too subjective.
If you are planning to close this question: please comment with a suggestion for a more appropriate place to post.
I'm super new to django and python, and I'm building a test app that keeps track of employees and who their managers are.
I would like to set up the domain model so that there there is only one list of employees, any of which can be managers, and all of which can be managed by any other employee who is designated a manager.
To achieve this, I did a self-join on the Employee model and have an "is_manager" flag to keep track of who is a manager and who isn't (see model below).
Is an acceptable pattern?
I'm worried it violates a design principle I'm not considering and there's some hairy trap that I'm walking into as a noob.
Thank you very much for your time.
models.py for the app:
class OrganizationTitle(models.Model):
def __str__(self):
return "{}".format(self.organization_title_name)
organization_title_name = models.CharField(max_length=150, unique=True)
class ClassificationTitle(models.Model):
def __str__(self):
return "{}".format(self.classification_title_name)
classification_title_name = models.CharField(max_length=150, unique=True)
class WorkingTitle(models.Model):
def __str__(self):
return "{}".format(self.working_title_name)
working_title_name = models.CharField(max_length=150, unique=True)
class Category(models.Model):
def __str__(self):
return "{}".format(self.category_name)
category_name = models.CharField(max_length=150, unique=True)
class Department(models.Model):
def __str__(self):
return "{}".format(self.department_name)
department_name = models.CharField(max_length=150, unique=True)
class Employee(models.Model):
first_name = models.CharField(max_length=150)
last_name = models.CharField(max_length=150)
org_title = models.ForeignKey(OrganizationTitle, blank=True, null=True, on_delete=models.SET_NULL)
manager = models.ForeignKey('self', null=True, blank=True, on_delete=models.SET_NULL)
manager_email = models.EmailField(max_length=50, blank=True, null=True)
hire_date = models.DateField(blank=True, null=True)
classification_title = models.ForeignKey(ClassificationTitle, blank=True, null=True, on_delete=models.SET_NULL)
working_title = models.ForeignKey(WorkingTitle, blank=True, null=True, on_delete=models.SET_NULL)
email_address = models.EmailField(max_length=250, blank=False, unique=True,
error_messages={'unique': 'An account with this email exist.',
'required': 'Please provide an email address.'})
category = models.ForeignKey(Category, blank=True, null=True, on_delete=models.SET_NULL)
is_substitute = models.BooleanField(default=False)
department = models.ForeignKey(Department, blank=True, null=True, on_delete=models.SET_NULL)
is_active = models.BooleanField(default=True)
is_manager = models.BooleanField(default=False)
class Meta:
ordering = ('is_active', 'last_name',)
def __str__(self):
return "{}".format(self.first_name + ' ' + self.last_name)
That's perfectly fine.
I would recommend you to specify the related_name to keep your code more explicit:
manager = models.ForeignKey(..., related_name="managed_employees")
so then you can do something like:
bob.managed_employees.all()
Also, there are 2 things I would change (not your question but still regarding the models):
1.The manager_email field is redundant. I would remove it. You already have that information at tom.manager.email_address for example.
2.There are many fields that I would simply rename to name. For example:
class OrganizationTitle(models.Model):
def __str__(self):
return u"{}".format(self.name)
name = models.CharField(max_length=150, unique=True)
No need to call it organization_title_name. That's consistent with the first_name field (not employee_first_name).
Yes, this is an acceptable pattern. This is called a "recursive relationship", or "self referential foreign keys" and is a very common usecase in realworld applications.
Here is django's example supporting this usecase
Help!
I have the following 2 models:
class Account(models.Model):
username = models.OneToOneField(User, primary_key=True, unique=True)
receiveaddress = models.CharField(max_length=40, blank=True, null=True, unique=True)
balance = models.DecimalField(max_digits=16, decimal_places=8, default=0)
def __str__(self):
return str(self.username)
class Deposits(models.Model):
receiveaddress = models.CharField(max_length=40, blank=True, null=True, unique=True)
amount = models.DecimalField(max_digits=16, decimal_places=8, default=0)
user = ?????????????????
created_at = models.DateTimeField(auto_now_add=True)
updated_at = models.DateTimeField(auto_now=True)
confirmed = models.BooleanField(default=False)
accounted = models.BooleanField(default=False)
def __str__(self):
return str(self.receiveaddress)
Example:
Visualization
My problem:
I want "Deposits.user" to automatically reference the user to which this 'receiveaddress' belongs. In the example, that's TIM. I've wasted 6 hours trying to figure it out, what am I doing wrong?
Thanks in advance.
I think it' just a design matter. Why do you put two fields that have the same information, since the user has account with receiveaddress, adding the user as foreign key will be enough and cleaner, I suggest the following:
class Account(models.Model):
username = models.OneToOneField(User, primary_key=True, unique=True)
receiveaddress = models.CharField(max_length=40, blank=True, null=True, unique=True)
balance = models.DecimalField(max_digits=16, decimal_places=8, default=0)
def __str__(self):
return str(self.username)
class Deposit(models.Model):
amount = models.DecimalField(max_digits=16, decimal_places=8, default=0)
user = models.ForeignKey(User, related_name="deposits")
created_at = models.DateTimeField(auto_now_add=True)
updated_at = models.DateTimeField(auto_now=True)
confirmed = models.BooleanField(default=False)
accounted = models.BooleanField(default=False)
def __str__(self):
return str(self.user.account.receiveaddress)
NB: As a convention, models name should be always singular