Why different records in the model? - django

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.

Related

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

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

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]

django-import-export package get a Foreignkey value while Export to XL file

First pardon me for my bad english. I am very new in Django Framework. I want to Export a foreignkey value called title which is in 'Product' model. There is multiple Foreignkey Relations between different django app models. Please take a look below all of this models:
products/models.py
class Product(models.Model):
title = models.CharField(max_length=500)
brand = models.ForeignKey(
Brand, on_delete=models.CASCADE, null=True, blank=True)
image = models.ImageField(upload_to='products/', null=True, blank=True)
price = models.DecimalField(decimal_places=2, max_digits=20, default=450)
old_price = models.DecimalField(
default=1000, max_digits=20, decimal_places=2)
weight = models.CharField(
max_length=20, help_text='20ml/20gm', null=True, blank=True)
size = models.CharField(
max_length=10, help_text='S/M/L/XL/32/34/36', null=True, blank=True)
active = models.BooleanField(default=True)
timestamp = models.DateTimeField(auto_now_add=True)
update = models.DateTimeField(auto_now=True)
carts/models.py
class Entry(models.Model):
product = models.ForeignKey(Product, null=True, on_delete=models.CASCADE)
cart = models.ForeignKey(Cart, null=True, on_delete=models.CASCADE)
quantity = models.PositiveIntegerField(default=1)
price = models.DecimalField(default=0.00, max_digits=100, decimal_places=2)
last_purchase_price = models.DecimalField(
default=0.0, max_digits=20, decimal_places=15)
weight_avg_cost = models.DecimalField(
default=0.0, max_digits=20, decimal_places=15)
updated = models.DateTimeField(auto_now=True)
timestamp = models.DateTimeField(auto_now_add=True)
class Meta:
ordering = ['-timestamp']
And my working models is analytics/models.py, from where I want to export the product title in XL sheet.
class AllReportModel(models.Model):
# All report model
invoice = models.ForeignKey(Invoice, on_delete=models.CASCADE, null=True, blank=True)
ws_invoice = models.ForeignKey(WholesaleInvoice, on_delete=models.CASCADE, null=True, blank=True)
entry = models.ForeignKey(Entry, on_delete=models.CASCADE, null=True, blank=True)
stock_quantity = models.IntegerField()
timestamp = models.DateTimeField(auto_now_add=True)
update = models.DateTimeField(auto_now=True)
and Finally analytics/admin.py is :
class AllReportModelResource(resources.ModelResource):
class Meta:
model = AllReportModel
fields = ('id', 'invoice', 'ws_invoice', 'entry', 'stock_quantity')
class AllReportModelAdmin(ImportExportModelAdmin):
resource_class = AllReportModelResource
list_display = ['invoice', 'ws_invoice', 'entry', 'timestamp']
search_fields = ['invoice']
admin.site.register(AllReportModel, AllReportModelAdmin)
Help will be highly appreciated.
I've been into this situation before, its solution is very easy.
You can refer to django-import-export documentation for advanced data manipulation on export Click HERE.

Django filtered queryset in foreignkey lookup

I have a standard model with a foreignkey, in this case from biology: Seed to Taxon. The taxon model includes both Animal and Plant Taxon, and has a category column which is either zoology or botany
When I add a new Seed I get the expected dropdown list, but it supplies the zoology and botany options. How do I filter it so only the botany options are shown? I'm assuming this filter can be applied somewhere in the model? I've tried adding .filter() and .exclude() but they do nothing here.
class Taxon(models.Model):
taxon_id = models.AutoField(primary_key=True)
taxon = models.CharField(max_length=50, blank=True, null=True)
common_name = models.CharField(max_length=50, blank=True, null=True)
taxon = models.CharField(max_length=50, blank=False, null=False)
genus = models.CharField(max_length=50, blank=True, null=True)
category = models.CharField(max_length=50, blank=True, null=True)
# family_name = models.CharField(max_length=50, blank=True, null=True)
def __str__(self):
return str(self.taxon)
class Meta():
managed=False
db_table = 'kap\".\"taxon_manager'
ordering = ["genus","taxon"]
verbose_name_plural = "taxon"
class Seed(models.Model):
seed_id = models.AutoField(primary_key=True)
fraction_id = models.ForeignKey(Fraction, db_column='fraction_id', blank=True, null=True, on_delete = models.PROTECT)
taxon_id = models.ForeignKey(Taxon, db_column='taxon_id', blank=True, null=True, on_delete = models.PROTECT, related_name='seed_taxon')
weight_type = models.CharField(max_length=50)
weight = models.DecimalField(max_digits=10, decimal_places=3)
quantity_type = models.CharField(max_length=50)
quantity = models.IntegerField()
def __str__(self):
return str(self.taxon_id)
class Meta():
managed=False
db_table = 'kap\".\"seed'
ordering = ["taxon_id","fraction_id"]
verbose_name_plural = "seeds"
If the category field in your Taxon model is a choice between "zoology" and "botany", then I would make them choices like so:
class Taxon(models.Model):
ZOOLOGY = 0
BOTANY = 1
CATEGORY_CHOICES = (
(ZOOLOGY, 'Zoology'),
(BOTANY, 'Botany'),
)
<your other fields>
category = models.CharField(max_length=50, choices=CATEGORY_CHOICES, blank=True, null=True)
Then, if you want to filter inside your seed model, you could change your taxon_id field so that it includes limit_choices_to:
taxon_id = models.ForeignKey(
Taxon,
db_column='taxon_id',
limit_choices_to={'category': Taxon.BOTANY},
blank=True,
null=True,
on_delete = models.PROTECT,
related_name='seed_taxon'
)
I haven't explicitly tested this case, but something like the above should work. If you want to filter in other places, then the filter that Juan mentioned in the comment looks good.
Hope this helps.

Restrict choices using two foreignkey relationships in django

I have three models, a household model, a household-member model, and an occupations models as described below. I would like the occupations model to only show members that belong to a particular household (which is related to field sno). How does one do something like this?
Would be grateful for any help.
class Household(models.Model):
village = models.CharField(max_length=150, null=True, blank=True)
household_number = models.IntegerField(blank=True, null=True)
form_number = models.IntegerField(null=True,blank=True)
head_of_household = models.CharField(max_length=150, null=True, blank=True)
class member(models.Model):
sno = models.ForeignKey(Household, on_delete=models.CASCADE)
person_number = models.IntegerField(blank=True, null=True)
name = models.CharField(max_length=150, null=True, blank=True)
sex_choices2 = (
('M','Male'),
('F','Female'),
)
sex = models.CharField(max_length=3,choices=sex_choices2,blank=True, null=True)
age = models.CharField(max_length=30,blank=True, null=True)
class Meta:
unique_together = (("sno", "person_number"),)
def __unicode__(self):
return self.name
def __str__(self):
return self.name
class occupations(models.Model):
sno = models.ForeignKey(Household,on_delete=models.CASCADE)
person_number = models.IntegerField(blank=True, null=True)
name = models.ForeignKey(member, blank=True, on_delete=models.SET_NULL, null=True)
occupation = models.CharField(max_length=100, null=True, blank=True)
class Meta:
unique_together = (("sno", "person_number","occupation"),)