Accessing model through other model via django queryset - django

I need to access columns in particular table through foreign keys in another table. I wrote it in SQL, but how it will be in queryset language?
This is models.py
class carModel(models.Model):
id_car_model = models.IntegerField(primary_key=True)
id_car_mark = models.ForeignKey(carMark,on_delete=models.CASCADE)
name = models.CharField(max_length=255)
date_create = models.IntegerField(max_length=10,null=True)
date_update = models.IntegerField(max_length=10,null=True)
id_car_type = models.ForeignKey(carType,on_delete=models.CASCADE)
name_rus = models.CharField(max_length=255,null=True)
class CarParts(models.Model):
id_catalog = models.IntegerField(primary_key=True)
manufacturer = models.CharField(max_length=200,blank=True, null=True)
vendor_code = models.IntegerField(blank=True, null=True)
subgroup = models.CharField(max_length=200,blank=True, null=True)
title = models.CharField(max_length=200,blank=True, null=True)
side = models.CharField(max_length=200,blank=True, null=True)
description = models.CharField(max_length=200,blank=True, null=True)
model = models.CharField(max_length=200,blank=True, null=True)
trade_mark = models.CharField(max_length=200,blank=True, null=True)
original_number = models.CharField(max_length=200,blank=True, null=True)
request = models.CharField(max_length=200,blank=True, null=True)
price = models.IntegerField(blank=True, null=True)
sum = models.IntegerField(blank=True, null=True)
availability = models.CharField(max_length=200,blank=True, null=True)
class interimTable(models.Model):
id_interim = models.IntegerField(primary_key=True)
description = models.CharField(max_length=100,null=True)
id_catalog=models.ForeignKey(CarParts, on_delete=models.CASCADE)
id_car_model = models.ForeignKey(carModel,on_delete=models.CASCADE)
This is SQL request, that is successful. I need same thing, but like querySet, to use it in further code.
Select title,side,price
from carinfo_carparts,carinfo_interimtable,carinfo_carmodel
where id_catalog = carinfo_interimtable.id_catalog_id
and carinfo_carmodel.id_car_model = carinfo_interimtable.id_car_model_id
and carinfo_carmodel.name='Civic';
this is the result

Try this,
CarParts.objects.filter(interimtable__id_car_model__name='Civic').values('title', 'side', 'price')

Related

How to get difference between two annotate fields in django orm

The problem is that with this approach, annotate ignores equal amounts, and if you remove distinct=True, then there will be duplicate objects and the difference will not be correct.
In simple words, I want to get the balance of the account by getting the difference between the amount in cash and the amount on receipts for this personal account
queryset = PersonalAccount.objects.select_related(
'apartment', 'apartment__house', 'apartment__section', 'apartment__owner',
).annotate(
balance=
Greatest(Sum('cash_account__sum', filter=Q(cash_account__status=True), distinct=True), Decimal(0))
-
Greatest(Sum('receipt_account__sum', filter=Q(receipt_account__status=True), distinct=True), Decimal(0))
).order_by('-id')
class PersonalAccount(models.Model):
objects = None
class AccountStatus(models.TextChoices):
ACTIVE = 'active', _("Активен")
INACTIVE = 'inactive', _("Неактивен")
number = models.CharField(max_length=11, unique=True)
status = models.CharField(max_length=8, choices=AccountStatus.choices, default=AccountStatus.ACTIVE)
apartment = models.OneToOneField('Apartment', null=True, blank=True, on_delete=models.SET_NULL,
related_name='account_apartment')
class CashBox(models.Model):
objects = None
number = models.CharField(max_length=64, unique=True)
date = models.DateField(default=datetime.date.today)
status = models.BooleanField(default=True)
type = models.BooleanField(default=True)
sum = models.DecimalField(max_digits=10, decimal_places=2)
comment = models.TextField(blank=True)
payment_items = models.ForeignKey('PaymentItems', blank=True, null=True, on_delete=models.SET_NULL)
owner = models.ForeignKey(User, blank=True, null=True, on_delete=models.SET_NULL, related_name='owner')
manager = models.ForeignKey(User, null=True, on_delete=models.SET_NULL, related_name='manager')
personal_account = models.ForeignKey('PersonalAccount', blank=True, null=True,
on_delete=models.SET_NULL, related_name='cash_account')
receipt = models.ForeignKey('Receipt', blank=True, null=True, on_delete=models.SET_NULL)
class Receipt(models.Model):
objects = None
class PayStatus(models.TextChoices):
PAID = 'paid', _("Оплачена")
PARTIALLY_PAID = 'partially_paid', _("Частично оплачена")
NOT_PAID = 'not_paid', _("Не оплачена")
number = models.CharField(max_length=64, unique=True)
date = models.DateField(default=datetime.date.today)
date_start = models.DateField(default=datetime.date.today)
date_end = models.DateField(default=datetime.date.today)
status = models.BooleanField(default=True)
status_pay = models.CharField(max_length=15, choices=PayStatus.choices, default=PayStatus.NOT_PAID)
sum = models.DecimalField(max_digits=10, decimal_places=2, default=0.00, blank=True)
personal_account = models.ForeignKey('PersonalAccount', blank=True, null=True,
on_delete=models.CASCADE, related_name='receipt_account')
tariff = models.ForeignKey('Tariff', null=True, on_delete=models.CASCADE)
apartment = models.ForeignKey('Apartment', null=True, on_delete=models.CASCADE,
related_name='receipt_apartment')

create custom view permission in django

I need to create a permission that allows the User to see the "Alumno" model, but I only need it to see the records of that model that have the same foreign key as "id_colegio"...
for example, if my User has the foreign key of id_colegio = 1, I need him to be able to see all the records of "Alumno" whose foreign key "id_colegio" = 1
models.py
class User(AbstractUser):
profesor = models.BooleanField(default=False)
rut_user = models.IntegerField(null=True)
id_colegio = models.ForeignKey('Colegio', models.DO_NOTHING, db_column='id_colegio',
null=True,verbose_name="Colegio")
class Alumno(models.Model):
rut_alumno = models.IntegerField(primary_key=True)
dv_alumno = models.CharField(max_length=1)
p_nombre = models.CharField(max_length=15 , verbose_name = "Primer nombre")
s_nombre = models.CharField(max_length=15, blank=True, null=True)
ap_paterno = models.CharField(max_length=15)
ap_materno = models.CharField(max_length=15, blank=True, null=True)
fecha_nac = models.DateField()
genero = models.CharField(max_length=1)
direccion = models.CharField(max_length=25, blank=True, null=True)
nivel_socio = models.CharField(max_length=10)
id_examenes = models.OneToOneField('ExamenCono', models.DO_NOTHING,
db_column='id_examenes')
rut_apoderado = models.ForeignKey('Apoderado', models.DO_NOTHING,
db_column='rut_apoderado')
id_colegio = models.ForeignKey('Colegio', models.DO_NOTHING, db_column='id_colegio')
id_curso = models.ForeignKey('Curso', models.DO_NOTHING, db_column='id_curso')
id_comuna = models.ForeignKey('Comuna', models.DO_NOTHING, db_column='id_comuna')
def __str__(self):
return f"{self.rut_alumno , self.p_nombre , self.ap_paterno}"
class Meta:
managed = True
db_table = 'alumno'
class Colegio(models.Model):
id_colegio = models.IntegerField(primary_key=True,verbose_name="Colegio")
nombre = models.CharField(max_length=20)
telefono = models.IntegerField(blank=True, null=True)
direccion = models.CharField(max_length=25)
id_comuna = models.ForeignKey('Comuna', models.DO_NOTHING, db_column='id_comuna')

how to call filter database with "Id " Django,

I want to make pay form, but I cannot show produk in orederitem, please helping me to show orderitem :v. I am really newbie in here .
models.py
class Order(models.Model):
name = models.ForeignKey(Profile, on_delete=models.SET_NULL, blank=True, null=True)
order_data = models.DateTimeField(auto_now_add=True)
selesai = models.BooleanField(default=False, blank=True, null=True)
status = models.BooleanField(default=False, blank=True, null=True)
id_transaksi = models.CharField(max_length=200, null=True)
bukti = models.ImageField(null=True, blank=True)
ongkir = models.CharField(max_length=200, null=True)
total = models.CharField(max_length=200, null=True)
total_harga = models.CharField(max_length=200, null=True)
pembayaran = models.CharField(max_length=200, null=True)
class OrderItem(models.Model):
product = models.ForeignKey(Product, on_delete=models.SET_NULL, blank=True, null=True)
order = models.ForeignKey(Order, on_delete=models.SET_NULL, blank=True, null=True)
quantity = models.IntegerField(default=0)
date_added = models.DateTimeField(auto_now_add=True)
views.py
def pembayaran(request):
customer = request.user.profile
ido = Order.objects.filter(id)
orders = Order.objects.filter(name=customer, selesai=True)
pengiriman = Pengiriman.objects.filter(name=customer)
OrderItems = OrderItem.objects.filter(order=ido)
print(OrderItems)
context = {'orders': orders,'pengiriman' :pengiriman , 'OrderItems': OrderItems }
return render(request, 'store/pembayaran.html', context)

Django - edit many-to-many inline

I have following model
class Day(models.Model):
date = models.DateField(auto_now=False, auto_now_add=False)
price = models.FloatField()
payment_method = models.CharField(max_length = 200, blank=True)
payment_date = models.CharField(max_length=200, blank=True)
room = models.ForeignKey(Room, null=True, blank=True, verbose_name='Номер', on_delete=models.CASCADE)
def __unicode__(self):
return str(self.date)
class Reservation(models.Model):
start = models.DateField(verbose_name='Заезд', auto_now=False, auto_now_add=False, blank=False)
end = models.DateField(verbose_name='Выезд', auto_now=False, auto_now_add=False, blank=False)
check_in_time = models.TimeField(verbose_name='Время заезда', blank=False)
check_out_time = models.TimeField(verbose_name='Время выезда', blank=False)
has_refund = models.BooleanField(verbose_name='Возвратная бронь', default=True)
payed = models.BooleanField(verbose_name='Оплачено', default=False)
reserved_days = models.ManyToManyField(Day, blank=False)
additional_services = models.ManyToManyField(AdditionalService)
guest_name = models.CharField(verbose_name='Имя гостя', max_length=200, blank=True)
reservation_number = models.CharField(verbose_name='Номер брони', max_length=200, blank=True)
What I want is to have ability to edit Day on Reservation page
I try the following as in the django docs
class ReservedDaysInline(admin.TabularInline):
model = Reservation
extra = 1
class ReservationAdmin(admin.ModelAdmin):
inlines = (ReservedDaysInline,)
class DayAdmin(admin.ModelAdmin):
inline = (ReservedDaysInline,)
admin.site.register(Reservation, ReservationAdmin)
admin.site.register(Day, DayAdmin)
But it doesnt work.
What am I doing wrong ?
Try this from doc
class ReservedDaysInline(admin.TabularInline):
model = Reservation.reserved_days.through
extra = 1
class ReservationAdmin(admin.ModelAdmin):
inlines = (ReservedDaysInline,)
exclude = ('reserved_days',)

Django filter queryset if a field exists

I want to filter my queryset if and only if loan exists in my model ShgGroupLoanMarking.
class ShgGroupLoanMarking(models.Model):
shg = models.ForeignKey(Shg, null=True)
category = models.CharField(max_length=25, choices=GROUP_CATEGORY, default="shg_group")
msss = models.ForeignKey(Msss, null=True)
shgmember = models.ForeignKey(ShgMember, null=True)
loan = models.ForeignKey(Loan, null=True)
date_of_marking = models.DateField(null=True)
paid = models.CharField(max_length=100, null=True)
loan_amount = models.CharField(max_length=100, null=True)
service_charge = models.CharField(max_length=100, null=True)
description = models.CharField(max_length=100, null=True)
status = models.CharField(max_length=100, null=True)
print_status = models.BooleanField(default=False)
sent_to_bank_status = models.BooleanField(default=False)
receipt_number = models.IntegerField(default=0)
How do I implement this?
ShgGroupLoanMarking.objects.filter(loan__isnull=False)
or
ShgGroupLoanMarking.objects.exclude(loan=None)