Order by related fields of different models in Django Admin - python

I want to order by the business_name, but the ordering isn't working due to some relationships, below is my first model :
class LoanApplication(models.Model):
loan_id = models.CharField(
'Loan Application ID', max_length=40, unique=True, null=True,
blank=True)
loan_taker = models.ForeignKey(
CustomerProfile, on_delete=models.PROTECT, null=True, blank=True,
verbose_name='Customer Profile', related_name='loan_entries')
submitted_date = models.DateTimeField(
'Submitted Date', null=True, blank=True)
then, I have the CustomerProfile model as below :
class CustomerProfile(models.Model):
customer_id = models.CharField(
'Customer Profile ID', max_length=64, unique=True, null=True)
cooperation_partner = models.ForeignKey(
EmailUser, on_delete=models.PROTECT, null=True, blank=True,
verbose_name=_('Jurisdiction'), related_name='partner_user_profile')
user = models.OneToOneField(
EmailUser, on_delete=models.PROTECT, null=True, blank=True,
verbose_name=_('User'), related_name='user_profile')
tipster_partner = models.ForeignKey(
TipsterPartner, on_delete=models.PROTECT, null=True, blank=True,
verbose_name='Tipster Partner')
So, I wanted to point to the Business model , it's as below :
class Business(models.Model):
business_id = models.CharField(
'Business ID', max_length=64, unique=True, null=True, blank=True)
business_name = models.CharField(_('Business'), max_length=128)
business_address_street = models.CharField(
'Business Address Street', max_length=50, blank=True)
then, we have the last one which is the CustomerProfileBusiness as below :
class CustomerProfileBusiness(models.Model):
business = models.ForeignKey(
Business, on_delete=models.PROTECT, null=True, blank=True,
verbose_name=_('Business'),
related_name='customer_profile_relation')
correlative_id = models.CharField(
_('Business ID'), max_length=64, unique=True, blank=True, null=True)
customer_profile = models.ForeignKey(
CustomerProfile, on_delete=models.PROTECT,
verbose_name=_('Customer Profile'), blank=True, null=True,
related_name='business')
Now, I do the ordering in the Admin page of the LoanApplication as below, but it doesn't work:
#admin.register(LoanApplication, site=admin_site)
class LoanApplicationAdmin(admin.ModelAdmin):
ordering = (
'-modified',
'loan_taker__business__customer_profile_relation__business_name',
)
So my target is to sort the business_name in the ascending order but using a relationship approach in the Admin page of the LoanApplication

Related

Django project, data deleted from the database

I am new in web development with Django and MySQL database, I got to develop a web application with Django framework, after deployment of my project in the server.
after 2 months, I noticed that data from my order table was deleted as well as the data of one user is displayed in the profile of another,
I want to know what I must do as a test to know the PR eventual error and to stop the deletion of data in my database.
data often deleted in the order and customer table.
the ORDER model bind with a foreign key to other Model:
class Order(models.Model):
user = models.ForeignKey(User, null=True, blank=True, on_delete=models.CASCADE)
created = models.DateTimeField( auto_now_add=True, verbose_name=_('Creation Date'))
payed = models.DateTimeField( verbose_name=_('Payment Date'), default=datetime.now, null=True, blank=True)
reference = models.IntegerField( verbose_name=_('Order Reference'), default=0, null=True, blank=True )
customer = models.ForeignKey( Customers, verbose_name=_('Customer'), null=True, blank=True, on_delete=models.CASCADE )
company = models.ForeignKey( Compagnie, verbose_name=_('Company'), null=True, blank=True, on_delete=models.CASCADE )
class Customers(models.Model):
company = models.ForeignKey(
Compagnie,
verbose_name=_('Company'),
null=True,
blank=True,
on_delete=models.CASCADE
)
forename = models.CharField(
verbose_name=_('First Name'),
max_length=255,
null=True,
blank=True)
GENDER = [('M', _('Male')),
('F', _('Female'))]
gender = models.CharField(
verbose_name=_('Gender'),
max_length=1,
choices=GENDER,
null=True,
blank=True)
city = models.ForeignKey(
City,
verbose_name=_('City'),
null=True,
blank=True,
on_delete=models.CASCADE
)
additionalNum = models.CharField(
verbose_name=_('Additional Number:'),
max_length=60,
null=True,
blank=True,
)
adressCustomer = models.TextField(
verbose_name=_('Address Customer:'),
max_length=500,
null=True,
blank=True,
)
telCustomer = models.CharField(
verbose_name=_('Phone Customer:'),
max_length=30,
null=True,
blank=True,
)
emailCustomer = models.EmailField(
verbose_name=_('Email Customer:'),
null=True,
blank=True,
)
otherBuyerId = models.CharField(
verbose_name=_('Other Buyer ID:'),
max_length=50,
null=True,
blank=True
)
vatNumber = models.CharField(
max_length=120,
null=True,
verbose_name=_('Vat Number:'),
blank=True
)
needs_attention = models.BooleanField(
verbose_name=_('Needs attention'),
default=False)
biography = models.TextField(
verbose_name=_('Biography'),
null=True,
blank=True)
_is_updating_cache_fields = False
def get_name(self):
first = self.forename or ''
name = "%s" % (first)
return name.strip()
class Meta:
verbose_name = _('Customer')
verbose_name_plural = _('Customers')
def __unicode__(self):
return u'%s %s: %s' % (
type(self).__name__,
self.pk,
self.forename)
def __str__(self):
if self.forename:
return self.forename
else:
return "Unnamed"
Can someone give me an explanation for this problem?

Post returns 1364, Field 'ADD' doesn't have a default value

THe error upon clicking the POST button on Djangorest Form
The serializer:
class CreatePolicyBenefitsSerializer(serializers.ModelSerializer):
class Meta:
model = Policy
fields = ('company','name','benefits','price')
The views:
class CreatePolicyBenefits(CreateAPIView):
queryset = Policy.objects.all()
serializer_class = CreatePolicyBenefitsSerializer
The Policy Model
``
class Policy(TimeStampedModel):
POLICY_CHOICES = (
('life', 'Life'),
('health', 'Health'),
('home', 'Home'),
('car', 'Car'),
('vul', 'VUL'),
)
PREMIUM_INTERVALS = (
('one_time', 'One Time'),
('annual', 'Annual'),
('semi_annual', 'Semi Annual'),
('quarterly', 'Quarterly'),
('monthly', 'Monthly')
)
company = models.ForeignKey(
'Company', related_name='Policies', on_delete=models.CASCADE,
null=True, blank=True)
name = models.CharField(max_length=255, blank=True, null=True, default="")
description = models.TextField(blank=True, null=True, default="")
benefits = models.JSONField(null=True, blank=True)
price = models.DecimalField(max_digits=10, decimal_places=2, default=0)
category = models.CharField(
max_length=64, blank=True, null=True, choices=POLICY_CHOICES, default="")
premium_details = models.CharField(max_length=255, blank=True, null=True)
policy_details = models.CharField(max_length=255, blank=True, null=True)
available_premium_interval = models.CharField(
max_length=64, blank=True, null=True, choices=PREMIUM_INTERVALS)
icon_name = models.CharField(max_length=32, blank=True, null=True)
icon_file = models.FileField(
upload_to=upload_policy_icon, blank=True, null=True)
primary_color = models.CharField(max_length=32, blank=True, null=True)
# file=models.FilePathField(path=os.path.join(settings.MEDIA_ROOT, 'media'))
adminupload=models.FileField(upload_to=pdf_path,max_length=None)
pdfname=models.CharField(max_length=255, blank=True, null=True)
class Meta:
app_label = samplename
def __str__(self):
return '[%s] %s-%s' % (self.id, self.company, self.name)
Here the form
Is it possible when I hit POST button, the data can be displayed on the form? Thanks

Increase performance with prefetch and select related

I'm trying to export a csv with information from the model order which has a relation 1 to 1 with delivery channel and restaurant and a 1 to many relationship with orderlines. It is taking way too much time for download it (around 20 seconds for 10k lines).
This is my code:
orderlines = OrderLine.objects.select_related("product").only(
"product__display_name", "quantity", "paid_amount", "discount_amount"
)
return (
Order.objects.prefetch_related(Prefetch("orderlines", queryset=orderlines, to_attr="orderlines_list"))
.select_related("delivery_channel")
.select_related("restaurant")
)
These are my models:
class Order(TimeStampedModel, TenantModel):
id = models.AutoField
objects = OrderManager()
restaurant = models.ForeignKey(
Restaurant,
blank=False,
null=False,
on_delete=models.PROTECT,
help_text=_("References the restaurant the order is for"),
)
delivery_channel = models.ForeignKey(
DeliveryChannel,
blank=False,
null=False,
on_delete=models.PROTECT,
)
class Restaurant(TenantModel):
id = models.AutoField
name = models.CharField(max_length=255, blank=False, null=False, default="", unique=False)
class DeliveryChannel(models.Model):
id = models.AutoField
name = models.CharField(
max_length=255, blank=False, null=False, unique=True, default="",
)
class OrderLine(TimeStampedModel, TenantModel):
id = models.AutoField
order = models.ForeignKey(
Order,
blank=False,
null=False,
on_delete=models.CASCADE,
related_name="orderlines",
)
product = models.ForeignKey(
Product, blank=False, null=False, on_delete=models.CASCADE,
)
unit_price = models.DecimalField(
blank=False,
null=False,
max_digits=8,
decimal_places=2,
)
quantity = models.IntegerField(blank=False, null=False, unique=False)
paid_amount = models.DecimalField(
blank=False,
null=False,
max_digits=8,
decimal_places=2,
)
discount_amount = models.DecimalField(
blank=False,
null=False,
max_digits=8,
decimal_places=2,
help_text=_("Amount of the discount applied to the product"),
)
class Product(TenantModel):
id = models.AutoField
objects = ProductManager()
display_name = models.CharField(max_length=255, blank=False, null=False, unique=False)
I thought about using only in the end but I can't use it on orderlines as it is a 1 to many relationship. I'm stuck on how to improve the performance. Many thanks.
You can use .only(…) [Django-doc], but you need to add the foreign key to the model itself, otherwise this will result in another N+1 problem: where it will each time have to make a query to determine to what Order it belongs, so:
orderlines = OrderLine.objects.select_related('product').only(
'product__display_name',
# add ForeignKey to the Order object ↓
'quantity', 'paid_amount', 'discount_amount', 'order'
)
return Order.objects.prefetch_related(
Prefetch('orderlines', queryset=orderlines, to_attr='orderlines_list')
).select_related(
'delivery_channel'
'restaurant'
)

Django Admin, Collapsable text boxes

How do I get these Textboxes to be collapsible?
I went through the documentation and this is what I wrote, but the changes are not being reflected.
Also, Is there any alternative I can use instead of limiting the user to select a max of 2 project manager or testers or what ever user they want to specify?
(Is there a way such that, the user can click on a + button or something so that another user can be listed is what I mean)
class FlatPageAdmin(admin.ModelAdmin):
fieldsets = (
(None, {
'fields': ('Project_Name',
'Project_Description',
'Admin_Name',
'Admin_Mail_ID',
'Project_Manager_1',
'Project_Manager_1_Mail_ID',
'Technician_1',
'Technician_1_Mail_ID',
'Tester_1',
'Tester_1_Mail_ID',
'Status_of_the_project',
'Created',
'Finish_Date',
'Supporting_Documents',
)
}),
('Add More Users', {
'classes': ('collapse',),
'fields': ('Project_Manager_2',
'Project_Manager_2_Mail_ID',
'Technician_2',
'Technician_2_Mail_ID',
'Technician_3',
'Technician_3_Mail_ID',
'Additional_User_1',
'Additional_User_1_Type',
'Additional_User_1_Mail_ID',
'Additional_User_2',
'Additional_User_2_Type',
'Additional_User_2_Mail_ID',
'Additional_User_3',
'Additional_User_3_Type',
'Additional_User_3_Mail_ID',
),
}),
)
Below is exactly how I wrote my codes for the models.py
Project_Name = models.CharField(max_length=100)
Project_Description = models.CharField(max_length=100)
Admin_Name = models.ForeignKey(User, on_delete=models.CASCADE, related_name='User.Admin_Name_users+')
Admin_Mail_ID = models.EmailField(max_length=50)
Project_Manager_1 = models.ForeignKey(User, on_delete=models.CASCADE, related_name='User.Project_Manager_1_users+')
Project_Manager_1_Mail_ID = models.EmailField(max_length=50)
Project_Manager_2 = models.ForeignKey(User, on_delete=models.CASCADE, related_name='User.Project_Manager_2_users+', blank=True, null=True)
Project_Manager_2_Mail_ID = models.EmailField(max_length=50, blank=True, null=True)
Technician_1 = models.ForeignKey(User, on_delete=models.CASCADE, related_name='User.Technician_1_users+')
Technician_1_Mail_ID = models.EmailField(max_length=50)
Technician_2 = models.ForeignKey(User, on_delete=models.CASCADE, related_name='User.Technician_2_users+', blank=True, null=True)
Technician_2_Mail_ID = models.EmailField(max_length=50, blank=True, null=True)
Technician_3 = models.ForeignKey(User, on_delete=models.CASCADE, related_name='User.Technician_3_users+', blank=True, null=True)
Technician_3_Mail_ID = models.EmailField(max_length=50, blank=True, null=True)
Tester_1 = models.ForeignKey(User, on_delete=models.CASCADE, related_name='User.Tester_1_users+')
Tester_1_Mail_ID = models.EmailField(max_length=50, default='Example#gmail.com')
Additional_User_1 = models.ForeignKey(User, on_delete=models.CASCADE, related_name='User.Ad_1_users+', blank=True, null=True)
Additional_User_1_Type = models.CharField(max_length=18, choices=STATUS_CHOICE, blank=True, null=True)
Additional_User_1_Mail_ID = models.EmailField(max_length=50, blank=True, null=True)
Additional_User_2 = models.ForeignKey(User, on_delete=models.CASCADE, related_name='User.Ad_1_users+', blank=True, null=True)
Additional_User_2_Type = models.CharField(max_length=18, choices=STATUS_CHOICE, blank=True, null=True)
Additional_User_2_Mail_ID = models.EmailField(max_length=50, blank=True, null=True)
Additional_User_3 = models.ForeignKey(User, on_delete=models.CASCADE, related_name='User.Ad_1_users+', blank=True, null=True)
Additional_User_3_Type = models.CharField(max_length=18, choices=STATUS_CHOICE, blank=True, null=True)
Additional_User_3_Mail_ID = models.EmailField(max_length=50, blank=True, null=True)
Status_of_the_project = models.CharField(max_length=18, choices=STATUS_CHOICE_1)
Created = models.DateTimeField(auto_now_add=True, null=True, blank=True)
Finish_Date = models.DateTimeField(null=True, blank=True)
Supporting_Documents = models.FileField(null=True, blank=True)
The Django feature that you're looking for is called Inlines.

Filter one-to-many relationship

I'm using django-filter and I would like to ask you if it could filter one to many reliontionship because I did not found any doc or example even on StackOverflow., here are the model, the filter and the view
class Aliens(models.Model):
class Meta:
db_table = 'aliens'
verbose_name = ('Introduction Event')
verbose_name_plural = ('Introuction Events')
ordering = ['alien']
alien = models.OneToOneField(Taxonomy, verbose_name=u"Non-indigenous Species",
on_delete=models.CASCADE, null=True, blank=True)
#SpeciesName = models.CharField(max_length=100, verbose_name=u"Species Name", blank=True, null=True)
group = models.OneToOneField(Ecofunctional, verbose_name=u"Ecofunctional Group", on_delete=models.CASCADE,
blank=True, null=True, default='')
firstsight = models.IntegerField(('First Mediterranean Sighting'), choices=YEAR_CHOICES, blank=True, null=True)
med_citation = models.ForeignKey(biblio, verbose_name=u"Mediterranean first citation", on_delete=models.CASCADE,
null=True, blank=True)
origin = models.OneToOneField(Origin, on_delete=models.CASCADE, blank=True, null=True, default='',
verbose_name=u"Origin")
status = models.OneToOneField(SuccessType, on_delete=models.CASCADE, blank=True, null=True, default='',
verbose_name=u"Establishement")
created_by = CurrentUserField()
created_at = models.DateField('date of inclusion', blank=True, null=True, default=datetime.datetime.now())
photo = models.ImageField(upload_to='photos', blank=True, null=True)
vector = models.ManyToManyField(vectors, verbose_name=u"Vectors/Pathways")
updated_at = models.DateField('date of updating', blank=True, null=True, default=datetime.datetime.now())
updated_by = models.ForeignKey(User, on_delete=models.CASCADE, related_name='%(class)s_requests_updated',
default=CurrentUserField(), null=True)
notes = models.TextField(verbose_name='Notes', blank=True, null=True)
db_status = StateField(verbose_name='Species Status in the Db', blank=True, null=True)
def __str__(self): # __unicode__ on Python 2
return self.alien.SpeciesName
class Distributions(models.Model):
class Meta:
db_table = 'distributions'
verbose_name = ('verified occurence')
verbose_name_plural = ('verified occurences')
alien = models.ForeignKey(Aliens, verbose_name=u"Non-Indeginous Species", related_name='distributions',
on_delete=models.CASCADE, null=True, blank=True)
country = models.OneToOneField(Country, on_delete=models.CASCADE, verbose_name='Country', blank=True, null=True)
seas = models.OneToOneField(regionalseas, on_delete=models.CASCADE, verbose_name='Regional Sea', blank=True,
null=True)
MSFD = models.OneToOneField(MSFD, on_delete=models.CASCADE, verbose_name='MSFD/EcAp Sub-region', blank=True,
null=True)
area1stSighting = models.DateField('First Areas Sighting', blank=True, null=True, default=datetime.datetime.now())
AreaSuccessType = models.OneToOneField(SuccessType, on_delete=models.CASCADE,
verbose_name='Area Establishement/Success', blank=True, null=True)
Area_citation = models.ForeignKey(biblio, verbose_name=u"Area first citation", on_delete=models.CASCADE, null=True,
blank=True)
created_by = models.ForeignKey(User, on_delete=models.CASCADE, related_name='%(class)s_requests_created',
default='')
created_at = models.DateField('date of Edition', blank=True, null=True, default=datetime.datetime.now())
updated_by = models.ForeignKey(User, on_delete=models.CASCADE, related_name='%(class)s_requests_updated',
default='')
updated_at = models.DateField('date of updating', blank=True, null=True, default=datetime.datetime.now())
notes = models.TextField(verbose_name='Notes', blank=True, null=True)
dverification = StateField(verbose_name='Validated ')
def __str__(self): # __unicode__ on Python 2
return self.alien.SpeciesName
class AliensFilter(django_filters.FilterSet):
country = filters.ModelChoiceFilter(label='Country', queryset=Country.objects.all())
msfd = filters.ModelChoiceFilter(label='MSF/EcAp Subregions', queryset=MSFD.objects.all())
regseas = filters.ModelChoiceFilter(label='Regional Seas', queryset=regionalseas.objects.all())
vector = filters.ModelChoiceFilter(label='Vectors/Pathway', queryset=vectors.objects.all())
Species = filters.ModelChoiceFilter(label='Species Name', queryset=Taxonomy.objects.all())
class Meta:
model = Aliens
fields = (
'Species', 'group', 'origin', 'firstsight', 'status', 'vector', 'country', 'msfd', 'regseas')
def search(request):
Aliens_list = Aliens.objects.all().select_related('origin', 'status', 'group', 'Taxonomy')
aliens_filter = AliensFilter(request.GET, queryset=Aliens_list)
# return render(request, 'mamias/list.html', {'filter': aliens_filter})
return render(request, 'mamias/list2.html', {'filter': aliens_filter})
How could I filter based on country for example?
There is no direct relationship between the Aliean and Country models. You would need to instead filter by country through the distributions relationship.
from django_filters import FilterSet, filters
class AlienFilter(FilterSet):
country = filters.ModelChoiceFilter(
field_name='distributions__country',
queryset=Country.objects.all(),
)

Categories

Resources