In Pegawai model, I need two ForeignKeys to:
Jabatan model
unit_kerja field of Jabatan model
How to apply these for my Pegawai model? Only the first one worked.
Here is my models.py:
from django.db import models
from django.urls import reverse
# Create your models here.
class UnitKerja(models.Model):
nama_unit_kerja = models.CharField(max_length=100)
def get_absolute_url(self):
return reverse("users:unitkerja")
def __str__(self):
return self.nama_unit_kerja
class Jabatan(models.Model):
nama_jabatan = models.CharField(max_length=100)
level_jabatan = models.IntegerField()
unit_kerja = models.ForeignKey(UnitKerja, on_delete=models.CASCADE, blank=True, null=True)
def get_absolute_url(self):
return reverse("users:jabatan")
def __str__(self):
return self.nama_jabatan
class Pegawai(models.Model):
nip = models.CharField(max_length=100, unique=True)
nama_pegawai = models.CharField(max_length=100)
alamat = models.CharField(max_length=255)
jabatan = models.ForeignKey(Jabatan, on_delete=models.CASCADE)
#this line#
unit_kerja = models.ForeignKey(Jabatan.unit_kerja, on_delete=models.CASCADE, blank=True, null=True)
def get_absolute_url(self):
return reverse("users:pegawai")
def __str__(self):
return self.pegawai
There is no such thing as a foreign key to a field, but you don't need it anyway. You can always access the UnitKerja instance by using multiple traversal, for example:
my_unit_kerja = my_pegawai.jabatan.unit_kerja
Or you can have a helper property, if the above is too much work:
class Pegawai(models.Model):
...
#property
def unit_kerja(self):
return self.jabatan.unit_kerja
and then simply use
my_pegawai.unit_kerja
Related
I have created a School System-like system, that creates a job and sends them to employees/users. I'm almost done making this system however I can't seem to know what do to check if the user is included in the manager model that I created to create a job.
Also, how can a user just see all their job that was assigned to them. All I know is to use objects.allbut that might only seem to show all of the jobs that was posted, I just want the user to see the job included to them.
Here is my model.py:
from django.db import models
from profiles.models import User
# Create your models here.
class Points (models.Model):
user = models.OneToOneField(User, on_delete=models.CASCADE)
points = models.IntegerField(default=0, null=False)
def __str__(self):
return self.user.username
class Profile (models.Model):
user = models.OneToOneField(User, on_delete=models.CASCADE)
image = models.ImageField(default='default.png',upload_to='profile_pics')
def __str__(self):
return f'{self.user.username}Profile'
class Manager (models.Model):
name = models.CharField(max_length=30, blank=True, null=True)
manager = models.ForeignKey(User,on_delete=models.CASCADE)
def __str__(self):
return self.name
class Member (models.Model):
name = models.CharField(max_length=30, blank=True, null=True)
manager = models.ForeignKey(Manager, on_delete=models.CASCADE)
member = models.ForeignKey(User,on_delete=models.CASCADE)
def __str__(self):
return self.name
class Job (models.Model):
manager = models.OneToOneField(Manager, on_delete=models.CASCADE)
member = models.OneToOneField(Member, on_delete=models.CASCADE)
title = models.CharField(max_length=30, blank=False, null=False)
description = models.TextField()
datePosted = models.DateTimeField (auto_now = True)
file = models.FileField(null=True, blank=True,upload_to='job_files')
def __str__(self):
return self.title
And Views.py:
from django.shortcuts import render
from django.views.generic import ListView, CreateView
from .models import Job
from profiles.models import User
# Create your views here.
class jobs(ListView):
model = Job
template_name = 'users/user_jobs.html'
context_object_name = 'jobs'
class createjob (CreateView):
model = Job
fields = ['member','title', 'description', 'file']
How can I proceed?
Use get_queryset to filter job by user
Ex:
class jobs(ListView):
model = Job
template_name = 'users/user_jobs.html'
context_object_name = 'jobs'
def get_queryset(self):
return Job.objects.filter(member__member=self.request.user)
I am a beginner in Django. I am building a data model for a Django app, named PhoneReview. It will store reviews related to the latest mobile phone. It's table should include:
a. Brand – details on brand, such as, name, origin, manufacturing since, etc
b. Model – details on model, such as, model name, launch date, platform, etc
c. Review – review article on the mobile phone and date published, etc
d. Many-to-many relationship between Review and Model.
Here are my codes in models.py:
from django.db import models
from django.template.defaultfilters import slugify
# Create your models here.
class Brand(models.Model):
brandName = models.CharField(max_length=100)
origin = models.CharField(max_length=100)
manufacturingSince = models.CharField(max_length=50, default='null')
def __str__(self):
return self.brandName
class PhoneModel(models.Model):
modelName = models.CharField(max_length=100)
launchDate = models.CharField(max_length=100)
platform = models.CharField(max_length=100)
def __str__(self):
return self.modelName
class Review(models.Model):
model_name_many_to_many = models.ManyToManyField(PhoneModel)
reviewArticle = models.CharField(max_length=1000)
datePublished = models.DateField(auto_now=True)
slug = models.SlugField(max_length=150, default='null')
def __str__(self):
return self.reviewArticle
Are my codes correct? Am I in the right direction?
Don't use camelCase in model fields. Use snake_case. Second thing is, when you want field to be default 'null', just use null=True, blank=True(optional value).
I've also provided related_name to your ManyToManyField, so you can use PhoneModelInstance.reviews.all() to get your all reviews for this specific Phone model. For large fields containing text, use TextField.
Edit
I've also added foreign key in PhoneModel which points to the Brand.
from django.db import models
from django.template.defaultfilters import slugify
# Create your models here.
class Brand(models.Model):
brand_name = models.CharField(max_length=100)
origin = models.CharField(max_length=100)
manufacturing_since = models.TextField(null=True, blank=True)
def __str__(self):
return self.brand_name
class PhoneModel(models.Model):
brand_fk = models.ForeignKey(Brand)
model_name = models.CharField(max_length=100)
launch_date = models.CharField(max_length=100)
platform = models.CharField(max_length=100)
def __str__(self):
return self.model_name
class Review(models.Model):
phone_model = models.ManyToManyField(PhoneModel, related_name='reviews')
review_article = models.TextField()
date_published = models.DateField(auto_now=True)
slug = models.SlugField(max_length=150, null=True, blank=True)
def __str__(self):
return self.review_article
I want to define a relationship between Book and Member through Borrow in models.py
ER
But I don't know how to define the Borrow relationship.
In the Borrow table it must be determined which books have been borrowed by who and which books have been returned on which date. Should I use another table for this date field?
models.py
from django.contrib.auth.models import AbstractUser
from django.db import models
from django.utils.translation import gettext as _
class CategoryType(models.Model):
category_name = models.CharField(max_length=200)
def __str__(self):
return self.category_name
class Book(models.Model):
name = models.CharField(verbose_name="عنوان", max_length=128)
number_of_copy = models.IntegerField(default=0)
writer = models.CharField(max_length=64)
B_category = models.ForeignKey(CategoryType, on_delete=models.CASCADE)
class Meta:
ordering = ["B_category"]
def __str__(self):
return self.name
class Borrow(models.Model):
borrowed_from_date = models.DateField(_("borrow Date"), default=0)
borrowed_to_date = models.DateField(_("return Date"), default=3)
actual_return_date = models.DateField()
borrowed_by = models.ForeignKey(member, on_delete=models.CASCADE)
books = models.ManyToManyField(Book)
def __str__(self):
return self.id
class Member(AbstractUser):
pass
I think in the Member class I should have a field containing borrow_id, but how?
It seems to me that you need to use a ManyToMany relationship with a through model (this way you can store extra information for every row of the Borrow model)
...
class Borrow(models.Model):
borrowed_from_date = models.DateField(_("borrow Date"), default=0)
borrowed_to_date = models.DateField(_("return Date"), default=3)
actual_return_date = models.DateField()
borrowed_by = models.ForeignKey(Member, on_delete=models.CASCADE)
book = models.ForeignKey(Book)
def __str__(self):
return self.id
...
class Member(AbstractUser):
borrowed_books = models.ManyToManyField(Book, through='Borrow')
Maybe this link (https://docs.djangoproject.com/es/2.1/ref/models/fields/#django.db.models.ManyToManyField.through) could clarify it more.
My problem whith django-autocomplete-light (dal 3) is that in the admin, instead of showing the choices corresponding tom my designated field (i.e. birth_nation see forms.py section), I always get a list of the str values of my queryset objects (see #models.py section) which is actually the last_name field.
# models.py
class MyModel(models.Model):
id_name = models.CharField(primary_key=True, max_length=255)
first_name = models.CharField(max_length=255, blank=True, null=True)
middle_name = models.CharField(max_length=255, blank=True, null=True)
last_name = models.CharField(max_length=255)
birth_city = models.CharField(max_length=255, blank=True, null=True)
birth_nation = models.CharField(max_length=255, blank=True, null=True)
def __str__(self):
return self.last_name
class Meta:
managed = False
db_table = 'mytable'
# forms.py
class MyModelForm(forms.ModelForm):
birth_nation = forms.ModelChoiceField(
queryset=MyModel.objects.all(),
widget=autocomplete.ModelSelect2(url='country-autocomplete',
attrs={'data-minimum-input-length': 2}
)
)
class Meta:
model = MyModel
fields = ('__all__')
# views.py
class MyModelAutocomplete(autocomplete.Select2QuerySetView):
def get_queryset(self):
if not self.request.user.is_authenticated():
return MyModel.objects.none()
qs = MyModel.objects.all()
if self.q:
qs = qs.filter(birth_nation__istartswith=self.q)
return qs
Obviously, I want to get my choices that correspond to the birth_nation, what is wrong in my code?
try this:
def __str__(self):
return self.birth_nation
Autocomplete return value is a query object. If you want to see specific field in the object, write that field in your model class or change your autocomplete class return value.
I would like to request some assistance regarding this matter,
I am fairly new to django and I like it so far.
I have the following model:
class Courses_list(models.Model):
Abbreviation = models.CharField(max_length=100, unique=True)
Course = models.CharField(max_length=100, unique=True)
def save(self, force_insert=False, force_update=False):
self.Abbreviation = self.Abbreviation.upper()
super(Courses_list, self).save(force_insert, force_update)
def __unicode__(self):
return self.Abbreviation
class Job_Posting(models.Model):
Job_Position = models.CharField(max_length=30, null=True, unique=True)
def __unicode__(self):
return self.Job_Position
class Educational_Requirement(models.Model):
fkey = models.ForeignKey('Job_Posting')
Course = models.ForeignKey('Courses_list')
And form:
class CustomField(forms.ModelChoiceField):
def label_from_instance(self, obj):
return obj.Course
class SampleForm(ModelForm):
COURSE = CourseField(queryset=Educational_Requirement.objects.all())
I am saving at:
class MyModel(ModelForm):
course = models.CharField(max_length=50, null = True, blank = True)
In the frontend of my test app SampleForm shows the Course as choices but how do I get the actual value of Course and save it? Because when I view my saved COURSE in the admin it displays Educational_Requirement Object instead of the value I have seen on the dropdown. I can't use __unicode__ at Educational_Requirement as it would raise an error.
I have updated my answer based on your updated question.
Why not use a ManyToManyField and let Django's ORM handle the educational_requirement relationship for you? This way you can use Django's reverse lookup to handle the ForeignKey's name.
class Courses_list(models.Model):
Abbreviation = models.CharField(max_length=100, unique=True)
Course = models.CharField(max_length=100, unique=True)
def save(self, force_insert=False, force_update=False):
self.Abbreviation = self.Abbreviation.upper()
super(Courses_list, self).save(force_insert, force_update)
def __unicode__(self):
return self.Abbreviation
class Meta:
verbose_name = 'Course'
verbose_name_plural = 'Courses'
class Job_Posting(models.Model):
Job_Position = models.CharField(max_length=30, null=True, unique=True)
educational_requirement = models.ManyToManyField(Courses_list)
def __unicode__(self):
return self.Job_Position
class Meta:
verbose_name = 'Job Position'
verbose_name_plural = 'Job Positions'