I have a QuerySet that I'm attempting to work with the values on related tables. I see the related tables/values when I run the queryset.query, however I'm not sure how to pull those values for use in forms/tables.
Here is my QuerySet Object:
tpList = AppCustomerTpRel.objects.filter(idcst_rel=selection).select_related('idcst_rel', 'idtrp_rel').values()
Here are the related Models.
class AppCustomerTpRel(models.Model):
id_rel = models.AutoField(primary_key=True)
idcst_rel = models.ForeignKey(AppCustomerCst, models.DO_NOTHING, db_column='idcst_rel')
idtrp_rel = models.ForeignKey(AppTradingPartnerTrp, models.DO_NOTHING, db_column='idtrp_rel')
cust_vendor_rel = models.CharField(max_length=50, blank=True, null=True)
sender_id_rel = models.CharField(max_length=50, blank=True, null=True)
old_vendor_rel = models.CharField(max_length=50, blank=True, null=True)
vendor_name_rel = models.CharField(max_length=50, blank=True, null=True)
category_rel = models.CharField(max_length=50, blank=True, null=True)
class AppTradingPartnerTrp(models.Model):
id_trp = models.AutoField(primary_key=True)
tpid_trp = models.CharField(max_length=50, blank=True, null=True)
name_trp = models.CharField(max_length=50)
description_trp = models.CharField(max_length=100, blank=True, null=True)
idtrn_trp = models.ForeignKey('AppTransmissionTrn', models.DO_NOTHING, db_column='idtrn_trp', blank=True, null=True)
class AppCustomerCst(models.Model):
id_cst = models.AutoField(primary_key=True)
is_active_cst = models.BooleanField()
name_cst = models.CharField(max_length=50, blank=True, null=True)
address_1_cst = models.CharField(max_length=50, blank=True, null=True)
address_2_cst = models.CharField(max_length=50, blank=True, null=True)
address_3_cst = models.CharField(max_length=50, blank=True, null=True)
city_cst = models.CharField(max_length=50, blank=True, null=True)
state_cst = models.CharField(max_length=50, blank=True, null=True)
zip_cst = models.CharField(max_length=10, blank=True, null=True)
country_cst = models.CharField(max_length=50, blank=True, null=True)
salesrep_cst = models.CharField(max_length=50, blank=True, null=True)
type_cst = models.CharField(max_length=10, blank=True, null=True)
is_allowed_flat_cst = models.BooleanField()
iddef_cst = models.IntegerField()
date_created_cst = models.DateTimeField()
date_suspended_cst = models.DateTimeField(blank=True, null=True)
date_first_tran_cst = models.DateTimeField(blank=True, null=True)
date_last_tran_cst = models.DateTimeField(blank=True, null=True)
is_credit_hold_cst = models.BooleanField()
old_balance_cst = models.DecimalField(max_digits=8, decimal_places=2)
balance_notify_cst = models.DecimalField(max_digits=8, decimal_places=2)
balance_statement_cst = models.DecimalField(max_digits=8, decimal_places=2)
balance_conversion_cst = models.DecimalField(max_digits=8, decimal_places=2)
balance_cst = models.DecimalField(max_digits=8, decimal_places=2)
receive_emails_cst = models.BooleanField()
contact_domain_cst = models.CharField(max_length=100, blank=True, null=True)
I am trying to work with values from the 'AppCustomerTpRel' Table.
I have tried app_customer_tp_rel.id_rel as well as app_customer_tp_rel__id_rel with the SQL Table Names, I have also tried both using the Model Name AppCustomerTpRel
TIA!
Just wright all related fields the you need in values()
tpList = AppCustomerTpRel.objects.filter(
idcst_rel=selection
).select_related(
'idcst_rel',
'idtrp_rel'
).values(
'idtrp_rel__id_trp',
'idtrp_rel__tpid_trp',
'idtrp_rel__name_trp',
...
)
Related
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')
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)
I need to have multiple editable rows Header and Items of products and variants of products in Django Admin change_list.html / change_list_results.html like the image below:
Example result
this is my model:
class VariantProduct(models.Model):
product = models.ForeignKey(Product, verbose_name=_('Prodotto'), related_name='variants', on_delete=models.CASCADE)
sku = models.CharField(_('SKU'), max_length=40, blank=True, null=True,
help_text='SKU', unique=True)
ean_13 = models.BigIntegerField('EAN 13',
validators=[MaxValueValidator(9999999999999, "Ammessi massimo 13 numeri.")],
blank=True, null=True, help_text='Codice numerico EAN 13')
ean_128 = models.CharField('EAN-128', max_length=128, blank=True, null=True,
help_text='Codice alfanumerico 128')
qr_code = models.CharField("Codice QR", blank=True, null=True, max_length=255,
help_text="digitare il codice per la generazione del QR Code")
barcode = models.ImageField('Barcode', upload_to='barcode/', blank=True, null=True)
quantity = models.IntegerField('Quantità', blank=True, null=True)
class Meta:
verbose_name = _('prodotto')
verbose_name_plural = _("prodotti")
ordering = ['name']
class VariantProduct(models.Model):
product = models.ForeignKey(Product, verbose_name=_('Prodotto'), related_name='variants', on_delete=models.CASCADE)
sku = models.CharField(_('SKU'), max_length=40, blank=True, null=True,
help_text='SKU', unique=True)
ean_13 = models.BigIntegerField('EAN 13',
validators=[MaxValueValidator(9999999999999, "Ammessi massimo 13 numeri.")],
blank=True, null=True, help_text='Codice numerico EAN 13')
ean_128 = models.CharField('EAN-128', max_length=128, blank=True, null=True,
help_text='Codice alfanumerico 128')
qr_code = models.CharField("Codice QR", blank=True, null=True, max_length=255,
help_text="digitare il codice per la generazione del QR Code")
barcode = models.ImageField('Barcode', upload_to='barcode/', blank=True, null=True)
quantity = models.IntegerField('Quantità', blank=True, null=True)
qta_stock_add = models.PositiveSmallIntegerField('Q.ta +', help_text='Diminuisci N. Prodotti', blank=True,
null=True, )
qta_stock_sub = models.PositiveSmallIntegerField('Q.ta -', help_text='Diminuisci N. Prodotti', blank=True,
null=True, )
minimal_quantity = models.IntegerField('Scorta Minima', blank=True, null=True,
help_text='Scorta minima di magazzino, può essere negativa per gestione sotttottoscorta')
image = models.ImageField(upload_to='prodotti/%Y/%m/%d',
verbose_name=_('Immagine Variante'), blank=True, null=True)
state = models.BooleanField('Attivo', help_text='Stato della variante prodotto attivo/disattivo', default=True)
price = models.DecimalField(_('Prezzo'), max_digits=8, decimal_places=2, default=0.00)
dealer_price = models.DecimalField(_('Prezzo Rivenditore'), max_digits=8, decimal_places=2, default=0.00)
size = models.ForeignKey(Size, verbose_name=_('Taglia'), blank=True, null=True, on_delete=models.PROTECT)
color = models.ForeignKey(Color, verbose_name=_('colore'), blank=True, null=True, on_delete=models.PROTECT)
weight = models.DecimalField(_('Peso gr.'), blank=True, null=True, decimal_places=2, max_digits=10,
help_text=_('Peso in grammi'))
height = models.IntegerField(_('Altezza cm'), blank=True, null=True,
help_text=_('Altezza in grammi'))
width = models.IntegerField(_('Larghezza cm'), blank=True, null=True,
help_text=_('Larghezza in grammi'))
length = models.IntegerField(_('Lunghezza cm'), blank=True, null=True,
help_text=_('Lunghezza in grammi'))
class Meta:
verbose_name = _('Variante Prodotto')
verbose_name_plural = _('Varianti Prodotto')
def __str__(self):
return '{cod} - {name}'.format(cod=self.sku, name=self.product.name)
Is possible to show on django admin page the row of a product an relative rows of variants and make editable the fields of "quantity" on all rows?
Thanks in advance.
W.
I have a models
class TDebtor(models.Model):
first_name = models.CharField(max_length=250, blank=True, null=True)
surname = models.CharField(max_length=250, blank=True, null=True)
middle_name = models.CharField(max_length=250, blank=True, null=True)
iin = models.CharField(max_length=50, blank=True, null=True)
alive = models.BooleanField(blank=True, null=True)
birth_date = models.DateField(blank=True, null=True)
class TDebtData(models.Model):
agr_num = models.CharField(max_length=250, blank=True, null=True)
id_num = models.CharField(max_length=250, blank=True, null=True)
loan_amount = models.DecimalField(max_digits=15, decimal_places=2, blank=True, null=True)
principal_amount = models.DecimalField(max_digits=15, decimal_places=2, blank=True, null=True)
id_debtor = models.ForeignKey('TDebtor', models.DO_NOTHING, related_name="debtor_debt_data")
views.py
class ProductList(ListAPIView):
queryset = TDebtor.objects.prefetch_related(Prefetch('debtor_debt_data', queryset=TDebtData.objects.select_related('id_debtor')))
for i in queryset:
print(i.debtor_debt_data.agr_num)
serializer_class = TDebtorSerializer
filter_backends = [DjangoFilterBackend]
filterset_fields = ['iin', 'first_name', 'surname', 'middle_name', 'birth_date',
'alive']
if I'll make a filter with the fields of TDebtor it's okay, but how I can filter with agr_num?, I mean if I'll send agr_num=1238HFD32 it will return me TDebtor that has this agr_num
Use RELATED_NAME__FIELD. In your case debtor_debt_data__agr_num
class ProductList(ListAPIView):
...
filterset_fields = [..., `debtor_debt_data__agr_num`]
Docs in https://django-filter.readthedocs.io/en/stable/index.html
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)