possible to split the model based on field in DRF admin.py - django

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

Related

Sum in Django Rest Framework (DRF) Serializer

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(),
})

How to display one models data in another model django admin panel

I have two models: 1) SchoolProfile & 2) Content
I want to show content data in schoolprofile, But data should be display as per user foreignkey.
User foreignkey common for both the models.
School Profile Model
class SchoolProfile(models.Model):
id=models.AutoField(primary_key=True)
user=models.ForeignKey(User,on_delete=models.CASCADE,unique=True)
school_name = models.CharField(max_length=255)
school_logo=models.FileField(upload_to='media/', blank=True)
incharge_name = models.CharField(max_length=255, blank=True)
email = models.EmailField(max_length=255, blank=True)
phone_num = models.CharField(max_length=255, blank=True)
num_of_alu = models.CharField(max_length=255, blank=True)
num_of_student = models.CharField(max_length=255, blank=True)
num_of_cal_student = models.CharField(max_length=255, blank=True)
def __str__(self):
return self.school_name
Content Model
class Content(models.Model):
id=models.AutoField(primary_key=True)
user=models.ForeignKey(User,on_delete=models.CASCADE)
content_type = models.CharField(max_length=255, blank=True, null=True)
show=models.ForeignKey(Show,on_delete=models.CASCADE, blank=True, null=True)
sponsor_link=models.CharField(max_length=255, blank=True, null=True)
status=models.BooleanField(default=False, blank=True, null=True)
added_on=models.DateTimeField(auto_now_add=True)
content_file=models.FileField(upload_to='media/', blank=True, null=True)
title = models.CharField(max_length=255)
subtitle = models.CharField(max_length=255, blank=True, null=True)
description = models.CharField(max_length=500, blank=True, null=True)
draft = models.BooleanField(default=False)
publish_now = models.CharField(max_length=255, blank=True, null=True)
schedule_release = models.DateField(null=True, blank=True)
expiration = models.DateField(null=True, blank=True)
tag = models.ManyToManyField(Tag, null=True, blank=True)
topic = models.ManyToManyField(Topic, null=True, blank=True)
category = models.ManyToManyField(Categorie, null=True, blank=True)
def __str__(self):
return self.title
I have used Inline but it's show below error:
<class 'colorcast_app.admin.SchoolProfileInline'>: (admin.E202) 'colorcast_app.SchoolProfile' has no ForeignKey to 'colorcast_app.SchoolProfile'.
My admin.py
class SchoolProfileInline(InlineActionsMixin, admin.TabularInline):
model = SchoolProfile
inline_actions = []
def has_add_permission(self, request, obj=None):
return False
class SchoolProfileAdmin(InlineActionsModelAdminMixin,
admin.ModelAdmin):
inlines = [SchoolProfileInline]
list_display = ('school_name',)
admin.site.register(SchoolProfile, SchoolProfileAdmin)
Using the StackedInline to link two models is straight forward and a much clean practice, so basically this is my solution below:
class ContentInlineAdmin(admin.StackedInline):
model = Content
#admin.register(SchoolProfile)
class SchoolProfileAdmin(admin.ModelAdmin):
list_display = ('school_name',)
inlines = [ContentInlineAdmin]

How can I post multiple object with form data via django rest framework

One company delivers multiple routes. How can I post the data via DRF?
There is an ImageField in DeliveryCompany
class DeliveryCompany(models.Model):
CompanyName = models.CharField("CRegNo", max_length=50, default=None, null=True, blank=True)
Address = models.CharField("CName", max_length=100, default=None, null=True, blank=True)
CompanyLogo = models.ImageField( default=None, null=True, blank=True)
class DeliveryRoute(models.Model):
Delivery = models.ForeignKey(DeliveryCompany, on_delete=models.CASCADE, default=None, null=True)
RouteFrom = models.CharField("RouteFrom", max_length=100, default=None, null=True, blank=True)
RouteTo = models.CharField("RouteTo", max_length=100, default=None, null=True, blank=True)
class DeliveryCompanySerializers(serializers.ModelSerializer):
deliveryRoute = serializers.SerializerMethodField()
class Meta:
model = DeliveryCompany
fields = '__all__'
def create(self, validated_data):
routes_data = validated_data.pop('routes')
delCom_obj = DeliveryCompany.objects.create(**validated_data)
for route in routes_data:
DeliveryRoute.objects.create(DeliveryCompany=DeliveryCompany, **routes_data)
return delCom_obj
def get_deliveryRoute(self, obj):
return DeliveryRouteSerializers(obj.deliveryroute_set.all(), many=True).data

Generic relation in Django rest

Problem
I want to create Student With Address. How can I write REST API in Django for same.
Address & Student
class Address(models.Model):
address = models.CharField(max_length=100, null=False, blank=False)
land_mark = models.CharField(max_length=100, null=True, blank=True)
city = models.CharField(max_length=100, null=True, blank=True)
state = models.CharField(max_length=100, null=True, blank=True)
pin_code = models.CharField(max_length=100, null=True, blank=True)
latitude = models.FloatField(default=0.0)
longitude = models.FloatField(default=0.0)
geo_code = models.CharField(max_length=100, null=True, blank=True)
content_type = models.ForeignKey(ContentType, on_delete=models.CASCADE,
null=True)
object_id = models.PositiveIntegerField()
content_object = GenericForeignKey('content_type', 'object_id')
class Student(models.Model):
name = model.CharField(max_length=100, null=False, blank=False)
address = GenericRelation(Address)
def __str__(self):
return self.name
Serializers
class AddressSerializer(serializers.ModelSerializer):
class Meta:
model = Address
fields = "__all__"
class StuddentSerializer(serializers.ModelSerializer):
class Meta:
model = Student
fields = "__all__"
API View
class AddressApiView(ListCreateAPIView):
queryset = Address.objects.all()
serializer_class = AddressSerializer
class StudentApiView(ListCreateAPIView):
queryset = Student.objects.all()
serializer_class = StuddentSerializer
How do I get my create/view student?
You can try with third-party app rest-framework-generic-relation link

Why different records in the model?

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.