display existing values of database into formfields - django-models

How can i get data from databse(sqllite) into dropdown button and based on selected value retrive all matching values on datagrid or in csv in django
class AnalyzedFile(models.Model):
sha256 = models.CharField(db_column='SHA256', max_length=64, blank=True)
md5 = models.CharField(db_column='MD5', max_length=32, blank=True)
sha1 = models.CharField(db_column='SHA1', max_length=40, blank=True)
filename = models.CharField(db_column='FILENAME', max_length=5000, blank=True)
filelength = models.IntegerField(db_column='FILELENGTH', blank=True, null=True)
filetype = models.CharField(db_column='FILETYPE', max_length=3, blank=True)
fileentropy = models.CharField(db_column='FILEENTROPY', max_length=50, blank=True)
peidsig = models.CharField(db_column='PEIDSIG', max_length=1000, blank=True)
exeinfosig = models.CharField(db_column='EXEINFOSIG', max_length=1000, blank=True)
ssdeepsig = models.CharField(db_column='SSDEEPSIG', max_length=200, blank=True)
digitalsig = models.CharField(db_column='DIGITALSIG', max_length=100, blank=True)
description = models.CharField(db_column='DESCRIPTION', max_length=65000, blank=True) # Field name made lowercase.
analysis = models.CharField(db_column='ANALYSIS', max_length=65000, blank=True)
class Meta:
managed = False
db_table = 'ANALYZED_FILE'

Related

I want to Join two tables each related (by a ForeignKey) to a third one (but not each other)

The three models relevant to this question are:
class MaterialList(models.Model):
org = models.ForeignKey(Organizations, on_delete=models.RESTRICT, blank=True)
Material = models.CharField(max_length=100)
Description = models.CharField(max_length=250, blank=True)
PartType = models.ForeignKey(WhsePartTypes, null=True, on_delete=models.RESTRICT)
Price = models.FloatField(null=True, blank=True)
PriceUnit = models.PositiveIntegerField(null=True, blank=True)
TypicalContainerQty = models.IntegerField(null=True, blank=True)
TypicalPalletQty = models.IntegerField(null=True, blank=True)
Notes = models.CharField(max_length=250, blank=True)
UniqueConstraint('org', 'Material')
class Meta:
ordering = ['org','Material']
class CountSchedule(models.Model):
org = models.ForeignKey(Organizations, on_delete=models.RESTRICT, blank=True)
CountDate = models.DateField(null=False)
Material = models.ForeignKey(MaterialList, on_delete=models.RESTRICT)
Counter = models.CharField(max_length=250, blank=True)
Priority = models.CharField(max_length=50, blank=True)
ReasonScheduled = models.CharField(max_length=250, blank=True)
Notes = models.CharField(max_length=250, blank=True)
UniqueConstraint('org', 'CountDate', 'Material')
class Meta:
ordering = ['org','CountDate', 'Material']
class ActualCounts(models.Model):
org = models.ForeignKey(Organizations, on_delete=models.RESTRICT, blank=False)
CountDate = models.DateField(null=False)
CycCtID = models.CharField(max_length=100, blank=True)
Material = models.ForeignKey(MaterialList, on_delete=models.RESTRICT)
Counter = models.CharField(max_length=250, blank=False, null=False)
LocationOnly = models.BooleanField(blank=True, default=False)
CTD_QTY_Expr = models.CharField(max_length=500, blank=False)
BLDG = models.CharField(max_length=100, blank=True)
LOCATION = models.CharField(max_length=250, blank=True)
PKGID_Desc = models.CharField(max_length=250, blank=True)
TAGQTY = models.CharField(max_length=250, blank=True)
FLAG_PossiblyNotRecieved = models.BooleanField(blank=True, default=False)
FLAG_MovementDuringCount = models.BooleanField(blank=True, default=False)
Notes = models.CharField(max_length = 250, blank=True)
class Meta:
ordering = ['org', 'CountDate', 'Material']
These models arise from a migration from a non-Python system to a Python-Django driven system. Most of the time, I only need the forward relations CountSchedule.Material and ActualCounts.Material. There is one report my bosses L_O_V_E, however. This report joins ActualCounts and CountSchedule where ActualCounts.CountDate=CountSchedule.CountDate and ActualCounts.Material=CountSchedule.Material. (Actually, the report has 3 sections, which boil down to a LEFT JOIN, a RIGHT JOIN and an INNER JOIN. For now, I just need help with any of these as a start).
For the moment, I'm going with raw SQL, but I'd like to know if the ORM has a solution.
Any advice?
I've already tried
M = MaterialList.objects.select_related('actualcounts_set', 'countschedule_set').filter(org=_userorg, actualcounts__CountDate=datestr, countschedule__CountDate=datestr)
which resulted in
Invalid field name(s) given in select_related: 'countschedule_set', 'actualcounts_set'. Choices are: org, PartType

filter objects by same value

Hey there i have a Order table which has created_at field, as multiple objects will be created at same date i want to list the objects by date.Such as i want to group the objects by date .Thank you.
#model
class SalesOrder(models.Model):
invoice_id = models.CharField(max_length=50, blank=True, null=True)
code = models.CharField(max_length=50, blank=True, null=True)
amount = models.FloatField(default=0.0, null=True, blank=True)
branch = models.ForeignKey('shop.Branch', on_delete=models.SET_NULL, null=True, blank=True)
customer = models.CharField(max_length=50, null=True, blank=True)
customer_contact = models.CharField(max_length=50, null=True, blank=True)
created_at = models.DateTimeField(auto_now_add=True)
def __str__(self):
return str(self.code)
def get_context_data(self, **kwargs): #View
cxt = super().get_context_data()
cxt['dates'] = SaleOrder.objects.annotate(
count=Count('created_at__date'))
# import pdb;pdb.set_trace()
cxt['form'] = SalesOrderForm(self.request.POST or None)

How To Spanning multi-valued relationships?

Im Try to Catch any data from database with table name is 'UserUsulan'.
I have two field, 'Ketua' and 'Anggota'.
In Ketua Field is ForeignKey from User, and Anggota is ManyToMany Field with relationship from User.
I want to render the data.
if in Ketua Field equal current.user render the data.
and also if current.user in Anggota field i want it render too.
So,
If the current.user is not able in Ketua Field, but able in Anggota Field. Render the Data
If the current.user is not able in Anggota Field, buat able in Ketua Field. Render the Data Too.
How To Solve this problem.
Im read with this documentation Spanning multi-valued relationships . But the Queryset is empty[].
models.py
tahun = models.IntegerField(_('year'), choices=YEAR_CHOICES, default=datetime.datetime.now().year)
judul_penelitian = models.TextField(blank=True)
jenis_penelitian = models.CharField(max_length=16, blank=True, default="", choices=JENIS_PENELITIAN_CHOICE)
tmt_awal = models.DateField(null=True, blank=True)
tmt_akhir = models.DateField(null=True, blank=True)
bidang_penelitian = models.CharField(max_length=10, blank=True, default="", choices=BIDANG_PENELITIAN_CHOICE)
tujuan_sosial_ekonomi = models.TextField(blank=True)
sumber_dana = models.CharField(max_length=30, blank=True, default="", choices=SUMBER_DANA_CHOICE)
skema_penelitian = models.CharField(max_length=15, blank=True, default="", choices=SKEMA_PENELITIAN_CHOICE)
jumlah_dana_usulan = MoneyField(max_digits=14, decimal_places=2, default_currency='IDR')
target_luaran = models.CharField(max_length=23, blank=True, default="", choices=TARGET_LUARAN_CHOICE)
ketua = models.ForeignKey(settings.AUTH_USER_MODEL, related_name='ketua_penelitian', on_delete=models.CASCADE, null=True, blank=True)
anggota = models.ManyToManyField(settings.AUTH_USER_MODEL, related_name='anggota_penelitian')
upload_file = models.FileField(upload_to='Penelitian/', null=True, blank=True)
status_usulan = models.CharField(max_length=8, blank=True, choices=STATUS_USULAN_CHOICE, default='MENUNGGU')
jumlah_dana_disetujui = MoneyField(max_digits=14, decimal_places=2, default_currency='IDR', null=True, blank=True)
keterangan_operator = models.TextField(null=True, blank=True)
com_reviewer_1 = models.TextField(null=True, blank=True)
com_reviewer_2 = models.TextField(null=True, blank=True)
views.py
def get_queryset(self):
queryset = super(UserUsulanPenelitianCreateAndListView, self).get_queryset()
queryset = queryset.filter(ketua=self.request.user,).filter(anggota=self.request.user,)
print(queryset)
return queryset
I Found The Answer, Using Q for the queryset
Import Q
from django.db.models import Q
Using Q in Queryset
def get_queryset(self):
queryset = super(UserUsulanPenelitianCreateAndListView, self).get_queryset()
queryset = queryset.filter(Q(ketua=self.request.user)|Q(anggota=self.request.user)).distinct()
print(queryset)
return queryset

Django models save 2 Foreinkeys to same Model

Following this link and documentation, somehow it still can't save an Object with 2 Foreinkeys.
class Photo(models.Model):
user = models.ForeignKey(User, on_delete=models.CASCADE, null=True) #User.photo_set.all() returns all Photo objects of the photo
photoURL = models.CharField(max_length=256, null=True)
secondPhoto = models.OneToOneField('self', on_delete=models.PROTECT, null=True, blank=True)
timestamp = models.DateTimeField(auto_now_add=True)
description = models.CharField(max_length=1000, null=True)
is_private = models.BooleanField(default=False)
class Clash(models.Model):
win_photo = models.ForeignKey(Photo,on_delete=models.PROTECT, related_name="wins", null=True)
loss_photo = models.ForeignKey(Photo,on_delete=models.PROTECT, related_name="losses", null=True)
is_private = models.BooleanField(default=False) #we will filter those out for user quality calculations

django insert data from 2 tables using a single ModelForm

I want to get data from 2 tables into a form using ModelForm, like this:
fist model:
class Cv(models.Model):
created_by = models.ForeignKey(User, blank=True)
first_name = models.CharField(('first name'), max_length=30, blank=True)
last_name = models.CharField(('last name'), max_length=30, blank=True)
url = models.URLField(verify_exists=True)
picture = models.ImageField(help_text=('Upload an image (max %s kilobytes)' %settings.MAX_PHOTO_UPLOAD_SIZE),upload_to='avatar')
bio = models.CharField(('bio'), max_length=180, blank=True)
expertise= models.ForeignKey(Expertise, blank=True)
date_birth = models.DateField()
second model:
class Expertise(models.Model):
user = models.ForeignKey(User, blank=True)
domain = models.CharField(('domain'), max_length=30, blank=True)
specialisation = models.CharField(('specialization'), max_length=30, blank=True)
degree = models.CharField(('degree'), max_length=30, blank=True)
year_last_degree = models.CharField(('year_last_degree'), max_length=30, blank=True)
lyceum = models.CharField(('lyceum'), max_length=30, blank=True)
faculty = models.CharField(('faculty'), max_length=30, blank=True)
references = models.CharField(('references'), max_length=30, blank=True)
workplace = models.CharField(('workplace'), max_length=30, blank=True)
then i have in forms.py
class CvForm(ModelForm):
class Meta:
model = Cv
fields = ['first_name','last_name','url','picture','bio','date_birth']
class ExpertiseForm(ModelForm):
class Meta:
model = Expertise
fields = ['domain','specialisation']
The point is that i would want to have the both forms into one single form, and a single submit of course. So, i guess i should use a single ModelForm type class. But it doesn't work (if i put the expertise in the CvForm too ).
My form is created automatically from the ModelForm class, that's why i want to make a single class = > a single form.
Help plss,
Thanks a lot
Since there is a foreign key from Expertise to CV, there are potentially multiple expertises for each cv. So you should enable that by using inline formsets.

Resources