The Loading time is too much for this particular model in admin panel.I know it is because I have too many values in Foreign Fields (field with 20k+ records each) which takes too much time to load on client side. Is there a way to optimise this? below is my code and screenshot of loadtime,
Loading Time
Models:
class Alert(BaseModelCompleteUserTimestamps):
type = models.ForeignKey(to=AlertType, on_delete=models.CASCADE, verbose_name="Type")
device = models.ForeignKey(Device, on_delete=models.CASCADE, related_name="alert_device")
device_event = models.ForeignKey("dm_detection.VIDSDetection",
on_delete=models.CASCADE, null=True, blank=True, related_name="device_event")
anpr_event = models.ForeignKey("dm_detection.VSDSDetection",
on_delete=models.CASCADE, null=True, blank=True, related_name="anpr_event")
ecb_event = models.ForeignKey("dm_detection.ECBDetection",
on_delete=models.CASCADE, null=True, blank=True, related_name="ecb_event")
hr_only = models.IntegerField(null=True, blank=True)
# acknowledged
is_acknowledged = models.BooleanField(default=False, verbose_name="Acknowledged")
acknowledged_at = models.DateTimeField(blank=True, null=True)
acknowledged_by = models.ForeignKey(to=User, on_delete=models.CASCADE, null=True, blank=True,
related_name="alert_acknowledged_by")
# resolved
is_resolved = models.BooleanField(default=False, verbose_name="Resolved")
resolved_at = models.DateTimeField(blank=True, null=True)
resolved_by = models.ForeignKey(to=User, on_delete=models.CASCADE, null=True, blank=True,
status = models.ForeignKey(to=TicketStatus, on_delete=models.DO_NOTHING, default=1)
Admin.py
#admin.register(Alert)
class AlertModelAdmin(BaseModelCompleteUserTimestampsAdmin):
form = AlertEditForm
fields = ('type',
'device',
'device_event',
'status', 'hr_only',
'is_acknowledged', 'acknowledged_at', 'acknowledged_by',
'is_resolved', 'resolved_at', 'resolved_by', 'anpr_event',
'created_at',
'updated_at', 'OD_vehicle_number'
)
Forms.py
class AlertEditForm(forms.ModelForm):
status = forms.ModelChoiceField(queryset=TicketStatus.objects.filter(is_for_alert=True))
device_event = forms.ModelChoiceField(queryset=VIDSDetection.objects.all())
anpr_event = forms.ModelChoiceField(queryset=VSDSDetection.objects.all())
acknowledged_by = forms.ModelChoiceField(queryset=User.objects.all())
resolved_by = forms.ModelChoiceField(queryset=User.objects.all())
class Meta:
model = Alert
fields = '__all__'
Related
Excuse me devs, i wanna ask about how to count on drf serializer, i need codes that can serialized fields plant from table A and it relations with another table B with count of them "plants_active"
Here's my code:
# Models
class TablePlants(models.Model):
plant_id = models.CharField(primary_key=True, max_length=20, unique=True)
gateway = models.ForeignKey(
TableGatewayDevice, models.DO_NOTHING, blank=True, null=True)
name = models.CharField(max_length=150, blank=True, null=True)
date = models.DateField(blank=True, null=True)
contact_person = models.CharField(max_length=70, blank=True, null=True)
contact_email = models.CharField(max_length=50, blank=True, null=True)
contact_phone = models.CharField(max_length=30, blank=True, null=True)
plant_status = models.CharField(max_length=20, blank=True, null=True)
weather_status_code = models.ForeignKey(
TableAuxWeather, models.DO_NOTHING, db_column='weather_status_code', blank=True, null=True)
timezone = models.CharField(max_length=200, blank=True, null=True)
image = models.FileField(
upload_to='plants/', validators=[file_size, validate_file_extension], null=True, blank=True)
class Meta:
db_table = 'table_plants'
def __str__(self):
return 'TablePlants[id: {id}, name: {name}]'.format(
id=self.id, name=self.name)
class PVOwner(models.Model):
pv_owner_id = models.AutoField(primary_key=True)
company = models.ForeignKey(TableCompany, on_delete=CASCADE,
blank=True, null=True, related_name="pv_owner_company")
class Meta:
db_table = 'table_pv_owner'
class TableSitePlant(models.Model):
pv_owner = models.ForeignKey(
PVOwner, on_delete=CASCADE, blank=True, null=True, related_name="pv_site_owner_plant")
site_owner = models.ForeignKey(
SiteOwner, on_delete=CASCADE, blank=True, null=True, related_name="site_owner_plant")
plant = models.ForeignKey(TablePlants, on_delete=CASCADE,
blank=True, null=True, related_name="site_plant")
class Meta:
db_table = 'table_site_plant'
# Serializer
class MainMenuSerializer(serializers.ModelSerializer):
plants_active = serializers.IntegerField(source="plant")
class Meta:
model = TableSitePlant
fields = ['plants_active']
# Views
#permission_classes([AllowAny])
class OverviewPlantsActiveView(generics.RetrieveAPIView):
queryset = TableSitePlant.objects.all().filter(plant__plant_status='offline')
serializer_class = OverviewPlantsActiveSerializer
lookup_field = 'pv_owner'
What i expecting is i can count how many plants that have status online
You can use the get method to return response as you desired.
#permission_classes([AllowAny])
class OverviewPlantsActiveView(generics.RetrieveAPIView):
queryset = TableSitePlant.objects.all().filter()
serializer_class = OverviewPlantsActiveSerializer
lookup_field = 'pv_owner'
def get(self, request):
queryset = self.get_queryset().filter(plant__plant_status='online')
return Response({
"active_plants": queryset.count(),
})
I am trying to obtain in a query the data of a client and the contacts he has registered I tried to do it in the following way but it did not work.
class ClientReadOnlySerializer(serializers.ModelSerializer):
clientcontacts = ClientContactSerializer(many=True, read_only=True)
class Meta:
model = Client
fields = "__all__"
Is there any way to make this relationship nested?
these are my models
clients model
# Relations
from apps.misc.models import City, TypeIdentity, TypeCLient, CIIU
from apps.clients.api.models.broker.index import Broker
from apps.authentication.models import User
class Client(models.Model):
id = models.CharField(max_length=255, unique=True,primary_key=True, editable=False)
type_client = models.ForeignKey(TypeCLient, on_delete=models.CASCADE, blank=True)
type_identity = models.ForeignKey(TypeIdentity, on_delete=models.CASCADE, blank=True)
document_number = models.CharField(max_length=255, blank=True, unique=True)
first_name = models.CharField(max_length=255, blank=True, null=True)
last_name = models.CharField(max_length=255, blank=True, null=True)
social_reason = models.CharField(max_length=255, blank=True, null=True)
city = models.ForeignKey(City, on_delete=models.CASCADE, blank=True)
address = models.CharField(max_length=255, blank=True)
email = models.CharField(max_length=255, blank=True, unique=True)
phone_number = models.CharField(max_length=255, blank=True, unique=True)
ciiu = models.ForeignKey(CIIU, on_delete=models.CASCADE, blank=True)
broker = models.ForeignKey(Broker, on_delete=models.CASCADE, blank=True)
user = models.ForeignKey(User, on_delete=models.CASCADE, blank=True)
income = models.SmallIntegerField(blank=True, default=0)
state = models.BooleanField(default=True)
created_at = models.DateTimeField(auto_now_add=True)
updated_at = models.DateTimeField(null=True, default=None)
client contacts model
# Relations
from apps.clients.api.models.index import Client
class ClientContact(models.Model):
id = models.CharField(max_length=255, primary_key=True, unique=True, editable=False)
client = models.ForeignKey(Client, on_delete=models.CASCADE)
first_name = models.CharField(max_length=255)
last_name = models.CharField(max_length=255)
phone_number = models.CharField(max_length=255)
state = models.BooleanField(default=True)
created_at = models.DateTimeField(auto_now_add=True)
updated_at = models.DateTimeField(null=True, blank=True, default=None)
after some research I came up with a solution that doesn't seem very practical, what I did was to create a method in the serializer that queries the client's contacts as follows
class ClientReadOnlySerializer(serializers.ModelSerializer):
contacts = serializers.SerializerMethodField(method_name='get_contacts')
class Meta:
model = Client
fields = "__all__"
extra_fields = ['contacts']
def get_contacts(self, obj):
contacts = ClientContact.objects.filter(client=obj)
serializer = ClientContactSerializer(contacts, many=True)
return serializer.data
using the model and the serializer of the contact model I made a query which I added in an extra field of the customer serializer, if someone knows how to make this process more optimal please reply.
I have model named organization. I am using this same model model for 2 api's. I have a field code. one API do code auto generation another API takes user entry code. I want to separate the tables based on code. Autogeneration code starts SUB001,SUB002,.... like wise. user entry code thats userwish.
models.py
class Organization(models.Model):
code = models.CharField(max_length=255, null=False, unique=True)
name = models.CharField(max_length=255, null=False)
organization_type = models.CharField(max_length=255, choices=TYPES, null=False, default=COMPANY)
internal_organization = models.BooleanField(null=False, default=True)
location = models.ForeignKey(Location, on_delete=models.RESTRICT)
mol_number = models.CharField(max_length=255, null=True, blank=True)
corporate_id = models.CharField(max_length=255, null=True, blank=True)
corporate_name = models.CharField(max_length=255, null=True, blank=True)
routing_code = models.CharField(max_length=255, null=True, blank=True)
iban = models.CharField(max_length=255, null=True, blank=True)
description = models.TextField(null=True, blank=True)
total_of_visas = models.IntegerField(null=False, default=0)
base_currency = models.ForeignKey(Currency, on_delete=models.RESTRICT, null=True, blank=True, default=None)
logo_filename = models.ImageField(_("Image"), upload_to=upload_to, null=True, blank=True)
def __str__(self):
return self.name
admin.py
#admin.register(Organization)
class OrganizationAdmin(admin.ModelAdmin):
list_display = (
'id',
'code',
'name',
'location',
'organization_type',
'internal_organization',
'mol_number',
'corporate_id',
'corporate_name',
'routing_code',
'iban',
'description',
'total_of_visas',
'base_currency',
'logo_filename',
)
Is there any possible to split models based on code,.. Really Expecting help...
You can use Proxymodel inheritance. Documentation
class AutoGenerationManager(models.Manager):
def get_queryset(self):
return super().get_queryset().filter(code__istartswith="SUB")
class AutoGeneration(Organization):
objects = AutoGenerationManager()
class Meta:
proxy = True
class UserGenerationManager(models.Manager):
def get_queryset(self):
return super().get_queryset().exclude(code__istartswith="SUB")
class UserGeneration(Organization):
objects = UserGenerationManager()
class Meta:
proxy = True
I am really confusing about Django joins. I want to search a keyword in two tables with a single query. can anyone help me?
the app model structure like this
class Events(models.Model):
event_type = models.CharField(_("Event Type"), max_length=5, choices=event_type_choices)
webinar_title = models.CharField(_("Webinar Title"), max_length=50, blank=True, null=True)
event_name = models.CharField(_("Event Name"), max_length=50, blank=True, null=True)
banner_title = models.CharField(_("Banner Title"), max_length=50, blank=True, null=True)
added_by = models.ForeignKey(User, null=True, blank=True, on_delete=models.SET_NULL)
status = models.BooleanField(_("Event Status"), default=True)
class Meta:
verbose_name = _('Event')
db_table = 'events'
app_label = 'events'
class WebinarSpeakers(models.Model):
event = models.ForeignKey(Events, on_delete=models.CASCADE, null=True)
speaker = models.CharField(_("Speaker Name"), max_length=100, null=True, blank=True)
job_title = models.CharField(_("Job Title"), max_length=255)
place_of_work = models.CharField(_("Place of Work"), max_length=100)
credentials = models.TextField(_("Credentials"), null=True, blank=True)
image = models.ImageField(_("Speaker Image"), upload_to=speaker_file_name, null=True, blank=True)
class Meta:
verbose_name = _('Event Webinar Speakers')
db_table = 'webinar_speakers'
app_label = 'events'
Now I want to search a keyword in webinar_title, evetn_name, banner_title, speaker, 'job_title` with a single query. how to do it in Django joins. I read the select_related document. it confusing me.
WebinarSpeakers.objects.filter(event__webinar_title="something", event__event_name="something", event__banner_title="somethng", speaker="something",job_title="something")
I have this abstract models.
class Abstract_Detail(models.Model):
""" Abstract models for detail in subassembly """
name = models.CharField(max_length=50, blank=True, null=True)
mark = models.CharField(max_length=50)
weight_end = models.FloatField(blank=True,
null=True, default=0)
class Meta:
abstract = True
unique_together = ('name', 'makr')
And Details model.
class Detail(Abstract_Detail):
""" Detail """
auto_area = models.FloatField(blank=True, null=True, default=0.0)
size_workpiece = models.CharField(max_length=10, blank=True, null=True)
weight = models.FloatField(blank=True, null=True, default=0)
product = models.ManyToManyField(Products, through='Structure_production')
subassembly = models.ManyToManyField(Subassembly, through='Structure_production')
material = models.ForeignKey(Material, on_delete=models.SET_NULL,
null=True, blank=True)
assortament = models.ForeignKey(Sortment, on_delete=models.SET_NULL,
null=True, blank=True)
class Meta():
unique_together = ('name', 'makr')
What is the problem: in some cases, when you change weight_end in admin Detail, when executing the below code, a new record is created with a combination of the name and mark, which is already in the model.
detail, sost = Detail.objects.get_or_create(
name=name, makr=makr,
defaults={'size_workpiece': size,
'material': material,
'assortament': sortament})
Is there an explanation? Read the documentation fully, the answer is not found.