I have master to child tables, need a solution to render it with below condition.
Master Table Fields:-
Person product categ price image field1 field2
Child Table (User customised):-
User Product categ customprice customfield1 customfield2
Query:-
totalrecords = Master.objects.filter(Person=person1).filter(categ=catogory1)
enabledrecords = Child.objects.filter(user=user).filter(categ=categ1)
product in child is foreign key from Master.
In template I will extract the master fields(in for loop) but if price and customfields exists in child then I need to take child object using product relation, otherwise populate these from master table.
Here the confusion comes,
{% for obj in totalrecords %}
if obj.id in enabledrecords (using product forign key) then
Get en_obj from enabledrecords__product
{{obj.id}} {{en_obj.id}} {%if en_obj.customprice%} {{en_obj.customprice}}
{%else%}{%obj.price%}{%endif%} -->do same for other customfields
if obj.id not in enabledrecords
{{ obj.id }} <p> Product not customized click here to customise </p>
Please advice.
EDIT:
Products(Master Table):-
vendor = models.ForeignKey(Shop,verbose_name='Shop Name')
name = models.CharField('Product Name', max_length=100 )
pfimage = models.ImageField('Image', upload_to='pd/%Y',)
pdctg = models.ForeignKey(PdCtg, null=True, blank=True, verbose_name='Product Category')
mrp =models.DecimalField('MRP (optional)',max_digits=6, decimal_places=2, null=True, blank=True)
ourprice =models.DecimalField('Our Price (optional)',max_digits=6, decimal_places=2, null=True, blank=True)
offer =models.CharField('Offers (optional)',max_length=10, null=True, blank=True)
Child Table:
vendor =models.ForeignKey(Shop,verbose_name='Shop Name')
pdctg = models.ForeignKey(PdCtg,null=True, blank=True,verbose_name='Product Category')
products =models.ForeignKey(Products, verbose_name='Product Name')
pdid =models.CharField('Item ID',max_length=100, null=True, blank=True)
mrp =models.DecimalField('MRP (optional)',max_digits=6, decimal_places=2, null=True, blank=True)
ourprice =models.DecimalField('Our Price (optional)',max_digits=6, decimal_places=2, null=True, blank=True)
offer =models.CharField('Offers (optional)',max_length=10, null=True, blank=True)
Child table may or may not have all rows of master for a given vendor and pdctg
Related
I'm trying to create a dashboard for orders placed by a customer. I've got multiple tables, but the two I'm dealing with is "Order" and "Order_Detail". From the "Order" table, I need to display Customer, Status, and Required_date, from the "Order_Detail" table, I need Product. I'm able to access the data but I can figure out how to display all the records at the same time on one page.
models.py
class Order(models.Model):
STATUS = (
('New', 'New'),
('Ready For Fullfillment', 'Ready For Fullfillment'),
('Fullfilled Ready For Delivery', 'Fullfilled Ready For Delivery'),
('Out For Delivery', 'Out For Delivery'),
('Delivered', 'Delivered'),
)
order_date = models.DateTimeField(auto_now_add=True, null=True)
required_date = models.DateTimeField(auto_now_add=True, null=True)
status = models.CharField(max_length=200, null=True, choices=STATUS)
note = models.CharField(max_length=1000, null=True, blank=True)
customer = models.ForeignKey(Customer, null=True, on_delete=models.SET_NULL)
def __str__(self):
return self.customer.name
class Order_Detail(models.Model):
orderNumber = models.ForeignKey(Order, null=True, on_delete=models.SET_NULL)
product = models.ForeignKey(Product, null=True, on_delete=models.SET_NULL)
pounds = models.IntegerField(null=True)
ounces = models.IntegerField(null=True)
container = models.ForeignKey(Container, null=True, on_delete=models.SET_NULL)
lot_code = models.CharField(max_length=200, null=True, blank=True)
note = models.CharField(max_length=1000, null=True, blank=True)
In my views.py, I'm playing with the following code:
print('TEST2')
o = Order.objects.all()
o_notdelivered = Order.objects.exclude(status='Delivered')
for e in o_notdelivered:
print('Order ID:', e.id)
order_detail_data = serializers.serialize("python", Order_Detail.objects.all().filter(orderNumber=e.id))
print('order_detail_data:', order_detail_data)
With that code, I'm able to get the ORDER data and related ORDER_DETAIL data, but I can't figure out how to put the fields I need together and send it to my template. Please note that their will be multiple orders and order_details that will need to go to the template.
Basically, in the end, I want, on my dashboard a table that looks like this:
|Customer|Product|Required Date|Status|
|-|-|-|-|
|C1|Product1|date here|New|
|C2|Product3|date here|New|
In your template (.html file) you have to access this variables, for example, if you want to show the status of all packages, then, in the html file you should write something like:
{% for object in o %} <!-- Works like in python-->
<h1>{{object.status}}</h1>
<!-- Do this for all other attributes-->
{% endfor %} <!-- Must close 'for loop'-->
use this query in your views Order_Detail.objects.all() and pass the context.
views.py
order_details = Order_Detail.objects.all()
context = {'order_details':order_details }
....your others code
then in your html:
{{order_details.product}} #accessing data from your Order_Detail model
{{order_details.orderNumber.status}} #accessing data from your Order model via foreignkey
I got such table structure
class Item(models.Model):
id = models.AutoField(primary_key=True)
class Car(models.Model):
vin_number = models.CharField(max_length=250, null=True, blank=True)
item = models.OneToOneField(Item, on_delete=models.CASCADE)
name = models.CharField(max_length=1000, null=True)
year = models.IntegerField(null=True)
class Yacht(models.Model):
name = models.CharField(max_length=1000, default='')
boat_type = models.CharField(max_length=1000, default='', null=True)
item = models.OneToOneField(Item, on_delete=models.CASCADE)
description = models.TextField(default='')
year = models.IntegerField(null=False, default=0)
So, both Car and Yacht has relation with Item table
If I have only item id in request, what is the right way to write such query
data = request.POST
item = Car.objects.filter(item_id=data['item_id']).first()
if not item:
item = Yacht.objects.filter(item_id=data['item_id']).first()
Is there any way not to use if/else statement?
You don't need to look into the Car and Yacht model. Directly use the Item model's OneToOne relationship
item = Item.objects.filter(id = data['id']).first
This item has a specific id that relates to one of the other model. You can access them using
if item.car:
car = item.car
else:
yacht = item.yacht
But I guess you also need to add {{ related_name='tags', related_query_name='tag' }} to your OneToOne field for both car and yacht.
I would recommend that you check this out https://kite.com/python/docs/django.db.models.ForeignKey.
For more detail go to https://docs.djangoproject.com/en/3.0/topics/db/examples/one_to_one/
You need to use exists().
Car.objects.filter(item_id=data['item_id']).exists()
Yacht.objects.filter(item_id=data['item_id']).exists()
It returns you True or False.
Links to official docs.
How can I associate a customer with a preorder object, while not creating a bunch of objects for that model? When the ManyToMany relationship is used in the admin change page, rather than allowing me to associate multiple customers with one Preorder, when I try to associate a customer with an instance of the Preorder model, it seems to create a new object, instead of updating the current Preorder instance to include a new customer to associate with it. I want something like this:
(customer: John, id=3) is associated with (Preorder: NewItem, id=1), and (customer: Kim, id=5) is also associated with (Preorder: NewItem, id=1). So John and Kim have both preordered NewItem where id=1, and if I were to select Preorder:NewItem, id=1 from a table, it would show that John and Kim have preorderd this item
I basically want to show a list that displays all customers that have preordered a specific product. Instead, at least with the ManyToMany field, when I click add next Many field display, it prompts me to create a new Preorder to associate with that customer, instead of selecting an already existing one. This results in each customer having the same preorder names associated, but these preorders will have different pk on the db table.
I have a Customer and Preorder model:
class Preorder(models.Model):
product = models.CharField(max_length=100, default='')
price = models.DecimalField(max_digits=12, decimal_places=2, default=None)
quantity = models.IntegerField(default=1, )
def __str__(self):
return self.product
class Customer(models.Model):
preorders = models.ManyToManyField(Preorder, blank=True, default=None)
name = models.CharField(max_length=100, default='')
email = models.EmailField(max_length=200, default='')
credit = models.DecimalField(max_digits=12, decimal_places=2, default=None, null=True, blank=True, verbose_name='Store Credit')
def __str__(self):
return self.name
Number of ways you could approach this, but it feels like you have your ManyToMany field the wrong way around:
class Preorder(models.Model):
product = models.CharField(max_length=100, default='')
price = models.DecimalField(max_digits=12, decimal_places=2, default=None)
quantity = models.IntegerField(default=1, )
customer = models.ManyToManyField(Customer, blank=True, default=None)
def __str__(self):
return self.product
That way, you have one pre-order with two customers (John and Kim) - so you're not duplicating your pre-order objects, or your user objects!
Then, in views.py:
def preorders(request, product):
context = {}
preorders = Preorder.object.filter(product=product)
return ...
And in urls.py something like this:
from django.conf.urls import url
urlpatterns = [
...
url(r'^preorders/(?P<product>\d+)/$', views.preorders, name='customer_preorders_by_product')),
...
]
And your template:
{% for preorder in preorders %}
<ul>
preorder.product
<li>{% for customer in preorder.customer.all %}{{ customer }}{% endfor %}</li>
</ul>
{% endfor %}
Hope that helps?
I want to export a database (15 or 20 tables) with Django (3, 000 rows and one hundred columns), but it takes very long.
I think the solution is to use prefetch_related, but I would like your opinion as it seems very complex to me (so many tables...). If this is the solution, can you show an example with a few different models?
def get_validated_acts(excl_fields_act_ids, excl_fields_act):
qs=Act.objects.filter(validated=2)
#list of acts
acts=[]
for act in qs.iterator():
#list of fields for one act
fields=[]
act_ids=ActIds.objects.get(act=act, src="index")
#ActIds
for field in ActIds()._meta.fields:
if field.name not in excl_fields_act_ids:
fields.append(getattr(act_ids, field.name))
#Act
for field in Act()._meta.fields:
if field.name not in excl_fields_act:
#CodeSect and related
if "code_sect_" in field.name:
temp=getattr(act, field.name)
if temp!=None:
fields.append(temp.code_sect)
fields.append(temp.code_agenda.code_agenda)
else:
fields.extend([None, None])
#Rapporteurs (Person) and related (oeil) or Responsibles (Person) and related (prelex)
elif "rapp_" in field.name or "resp_" in field.name:
temp=getattr(act, field.name)
if temp!=None:
fields.append(temp.name)
country=temp.country
party=temp.party
fields.append(country.country_code)
fields.append(party.party)
if "resp_" in field.name:
#party_family
fields.append(PartyFamily.objects.get(party=party, country=country).party_family)
else:
if "resp_" in field.name:
temp=[None]*4
else:
temp=[None]*3
fields.extend(temp)
else:
#for all the other non fk fields, get its value
fields.append(getattr(act, field.name))
#Act many to many fields
for field in Act()._meta.many_to_many:
#GvtCompo
if "gvt_compo"==field.name:
gvt_compos_country=gvt_compos_party=gvt_compos_party_family=""
#for each country
for gvt_compo in getattr(act, field.name).all():
country=gvt_compo.country
#for each party, add a "row" for each variable (country, party, party family)
for party in gvt_compo.party.all():
gvt_compos_country+=country.country_code+"; "
gvt_compos_party+=party.party+"; "
gvt_compos_party_family+=PartyFamily.objects.get(country=country, party=party).party_family+"; "
#delete last "; "
fields.append(gvt_compos_country[:-2])
fields.append(gvt_compos_party[:-2])
fields.append(gvt_compos_party_family[:-2])
#adopt_cs_contre, adopt_cs_abs, adopt_pc_contre, adopt_pc_abs
else:
countries=""
for country in getattr(act, field.name).all():
countries+=country.country_code+"; "
fields.append(countries[:-2])
#Ministers' attendance fields
instances=MinAttend.objects.filter(act=act)
temp_fields={"country": "", "verbatim": "", "status": ""}
for instance in instances:
temp_fields["country"]+=instance.country.country_code+"; "
temp_fields["verbatim"]+=instance.verbatim.verbatim+"; "
temp_fields["status"]+=Status.objects.get(verbatim=instance.verbatim, country=instance.country).status+"; "
fields.append(temp_fields["country"][:-2])
fields.append(temp_fields["verbatim"][:-2])
fields.append(temp_fields["status"][:-2])
acts.append(fields)
return acts
If it helps, here are some fields of the main model Act:
class Act(models.Model):
titre_en=models.CharField(max_length=1000, blank=True, null=True, default=None)
code_sect_1=models.ForeignKey(CodeSect, related_name='code_sect_1', blank=True, null=True, default=None)
code_sect_2=models.ForeignKey(CodeSect, related_name='code_sect_2', blank=True, null=True, default=None)
code_sect_3=models.ForeignKey(CodeSect, related_name='code_sect_3', blank=True, null=True, default=None)
code_sect_4=models.ForeignKey(CodeSect, related_name='code_sect_4', blank=True, null=True, default=None)
rep_en_1=models.CharField(max_length=200, blank=True, null=True, default=None)
rep_en_2=models.CharField(max_length=200, blank=True, null=True, default=None))
type_acte=models.CharField(max_length=100, blank=True, null=True, default=None)
com_amdt_tabled=models.IntegerField(max_length=3, blank=True, null=True, default=None)
votes_agst_1=models.IntegerField(max_length=3, blank=True, null=True, default=None)
rapp_1=models.ForeignKey(Person, related_name='rapp_1', blank=True, null=True, default=None)
rapp_2=models.ForeignKey(Person, related_name='rapp_2', blank=True, null=True, default=None)
rapp_3=models.ForeignKey(Person, related_name='rapp_3', blank=True, null=True, default=None)
rapp_4=models.ForeignKey(Person, related_name='rapp_4', blank=True, null=True, default=None)
adopt_propos_origine=models.DateField(max_length=10, blank=True, null=True, default=None)
com_proc=models.CharField(max_length=100, blank=True, null=True, default=None)
resp_1=models.ForeignKey(Person, related_name='resp_1', blank=True, null=True, default=None)
resp_2=models.ForeignKey(Person, related_name='resp_2', blank=True, null=True, default=None)
resp_3=models.ForeignKey(Person, related_name='resp_3', blank=True, null=True, default=None)
transm_council=models.DateField(max_length=10, blank=True, null=True, default=None)
adopt_cs_contre=models.ManyToManyField(Country, related_name='adopt_cs_contre')
adopt_cs_abs=models.ManyToManyField(Country, related_name='adopt_cs_abs')
adopt_pc_contre=models.ManyToManyField(Country, related_name='adopt_pc_contre')
adopt_pc_abs=models.ManyToManyField(Country, related_name='adopt_pc_abs')
gvt_compo=models.ManyToManyField(GvtCompo)
This code seems a bit faster (10% faster):
def get_validated_acts(excl_fields_act_ids, excl_fields_act):
tic=time.time()
#querysets
qs_act=Act.objects.defer("id", 'date_doc', "url_prelex", "validated", "validated_attendance").filter(validated=2).prefetch_related("gvt_compo", "adopt_cs_contre", "adopt_cs_abs", "adopt_pc_contre", "adopt_pc_abs").prefetch_related("gvt_compo__party")
qs_actids=ActIds.objects.defer("id", 'src', "url_exists", 'act').filter(src="index")
qs_cs=CodeSect.objects.all().prefetch_related("code_agenda", "config_cons")
qs_pers=Person.objects.all()
qs_party=Party.objects.all()
qs_pf=PartyFamily.objects.all()
qs_minattend=MinAttend.objects.all()
qs_verb=Verbatim.objects.all()
qs_status=Status.objects.all()
#fields names
names_actids=[field.name for field in ActIds()._meta.fields if field.name not in excl_fields_act_ids]
names_act=[field.name for field in Act()._meta.fields if field.name not in excl_fields_act]
names_act_m2m=[field.name for field in Act()._meta.many_to_many]
#list of acts
acts=[]
for act in qs_act:
#list of fields for one act
fields=[]
act_ids=qs_actids.get(act=act)
#ActIds
for field in names_actids:
fields.append(getattr(act_ids, field))
#Act
for field in names_act:
#CodeSect and related
if "code_sect_" in field:
cs_id=getattr(act, field+"_id")
if cs_id!=None:
cs=qs_cs.get(pk=cs_id)
fields.append(cs.code_sect)
fields.append(cs.code_agenda.code_agenda)
else:
fields.extend([None, None])
#Rapporteurs (Person) and related (oeil) or Responsibles (Person) and related (prelex)
elif "rapp_" in field or "resp_" in field:
pers_id=getattr(act, field+"_id")
if pers_id!=None:
pers=qs_pers.get(pk=pers_id)
party=qs_party.get(pk=pers.party_id)
fields.append(pers.name)
fields.append(pers.country_id)
fields.append(party.party)
if "resp_" in field:
#party_family
fields.append(qs_pf.get(party=party, country_id=pers.country_id).party_family)
else:
if "resp_" in field:
temp=[None]*4
else:
temp=[None]*3
fields.extend(temp)
else:
#for all the other non fk fields, get its value
fields.append(getattr(act, field))
#~
#Act many to many fields
for field in names_act_m2m:
#GvtCompo
if "gvt_compo"==field:
gvt_compos_country=gvt_compos_party=gvt_compos_party_family=""
#~ #for each country
for gvt_compo in act.gvt_compo.all():
#for each party, add a "row" for each variable (country, party, party family)
for party in gvt_compo.party.all():
gvt_compos_country+=gvt_compo.country_id+"; "
gvt_compos_party+=party.party+"; "
gvt_compos_party_family+=qs_pf.get(party=party, country_id=gvt_compo.country_id).party_family+"; "
#delete last "; "
fields.append(gvt_compos_country[:-2])
fields.append(gvt_compos_party[:-2])
fields.append(gvt_compos_party_family[:-2])
#~ #adopt_cs_contre, adopt_cs_abs, adopt_pc_contre, adopt_pc_abs
else:
countries=""
for country in getattr(act, field).all():
countries+=country.country_code+"; "
fields.append(countries[:-2])
#~
#Ministers' attendance fields
instances=qs_minattend.filter(act=act)
temp_fields={"country": "", "verbatim": "", "status": ""}
for instance in instances:
temp_fields["country"]+=instance.country_id+"; "
temp_fields["verbatim"]+=qs_verb.get(pk=instance.verbatim_id).verbatim+"; "
temp_fields["status"]+=qs_status.get(verbatim_id=instance.verbatim_id, country_id=instance.country_id).status+"; "
fields.append(temp_fields["country"][:-2])
fields.append(temp_fields["verbatim"][:-2])
fields.append(temp_fields["status"][:-2])
acts.append(fields)
tac=time.time()
print "time", tac-tic
return acts
I use prefetch_related and I store all the objects in memory. Not sure it is such a good idea...
I'm trying to get django-haystack (using a xapian backend) to index my model here for search, by the name and description fields.
I have a subclass of Item, Device, which adds a manufacturer field.
The Item model is defined thusly:
class Item(models.Model):
name = models.CharField(max_length=255, unique=True)
description = models.TextField(null=True, blank=True)
compatible_with = models.ManyToManyField('self', null=True, blank=True)
often_with = models.ManyToManyField('self', null=True, blank=True)
created_by = models.ForeignKey(User, null=True, blank=True, related_name='created_by')
verified = models.BooleanField(default=False)
verified_by = models.ForeignKey(User, null=True, blank=True, related_name='verified_by')
date_created = models.DateField(auto_now_add=True)
slug = models.SlugField(max_length=300, null=True, blank=True)
My subclass of django-haystack’s SearchIndex looks like this:
class ItemIndex(SearchIndex):
text = CharField(document=True, use_template=True)
name = CharField(model_attr='name')
description = CharField(model_attr='description')
site.register(Item, ItemIndex)
I have set up this template, in templates/search/indexes/catalog/item_text.txt:
{{ object.name }}
{{ object.description }}
What do I add to item_text.txt such that the manufacturer field gets indexed, if and only if the model object is an instance of Device?
{% if device.manufacturer %}
{{ device.manufacturer }}
{% endif %}
... the Haystack tutorial is a bit confusing on this subject (you don't actually have to use a text-file template, for one) but the basic idea is that Haystack's engine goes to town on whatever text data is in this template.
... Actually, it goes to town on whatever is in the response you send it, but if you've got the template set up you can use whatever Django template logic you want in there.
(note that the if template tag was a bit of a dog's breakfast prior to Django 1.2; if you're stuck on an earlier Django version you may have to tweak the syntax, but the principle is the same.)