Filter one-to-many relationship - python

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

Related

Serialize same level object from Many to many field

I have to serialize spare instance from spare variety many to many field.
Models.py
class SpareVariety(models.Model):
quality = models.ForeignKey(Quality, max_length=255, on_delete=models.CASCADE, null=True, blank=True)
variety_name = models.CharField(max_length=255, null=True, blank=True)
property = models.ForeignKey(SpareProperty, null=True, blank=True, on_delete=models.CASCADE)
purchase_price = models.PositiveIntegerField(help_text="in INR", blank=True, null=True)
retail_price = models.FloatField(help_text="All values in INR", blank=True, null=True)
dealer_price = models.FloatField(help_text="All values in INR", blank=True, null=True)
stock_available = models.PositiveIntegerField(blank=True, null=True,default=True)
spare_costing = models.ForeignKey(SpareCosting, on_delete=models.CASCADE, blank=True, null=True)
spare_discount = models.ForeignKey(Discount, on_delete=models.CASCADE, blank=True, null=True)
is_available = models.BooleanField(default=False)
date_added = models.DateTimeField(auto_now=True)
date_updated = models.DateTimeField(auto_now_add=True)
class Spare(models.Model):
product = models.ForeignKey(Product, on_delete=models.CASCADE)
spare_variety = models.ManyToManyField(SpareVariety, related_name='spare_varieties', null=True, blank=True)
name = models.CharField(max_length=255, help_text="Enter the name of spare (Ex:Display, Speakers)")
type = models.ForeignKey(Type, blank=True, null=True, on_delete=models.CASCADE)
date_added = models.DateTimeField(auto_now=True)
date_updated = models.DateTimeField(auto_now_add=True)
def __str__(self):
return '%s - %s' % (self.product.name, self.name)
Serialize the spare model from spare variety serializer
serializers.py
class SpareVarietySerializer(serializers.HyperlinkedModelSerializer):
spare_costing= SpareCostingSerializer(many=False, read_only=False)
spare_discount = DiscountSerializer(many=False, read_only=False)
quality = QualitySerializer(many=False, read_only=False)
property = SparePropertySerializer(many=False, read_only=False)
spare_name = serializers.CharField(read_only=True, source="spare.name")
class Meta:
model = SpareVariety
fields = ['id','quality','variety_name','purchase_price','spare_name','retail_price','property', 'dealer_price', 'stock_available','spare_costing','spare_discount','is_available', 'date_added', 'date_updated',]

Find pk in queryset Django

I have a problem in obtaining a single id from a queryset. I post my models and views in order to be more clear:
models.py
class MissionEntry(models.Model):
student = models.ForeignKey(
Student, on_delete=models.DO_NOTHING, blank=True, null=True)
mission = models.ForeignKey(
Mission, on_delete=models.DO_NOTHING, null=True, blank=True)
log_entry = models.ForeignKey(
LogEntry, on_delete=models.DO_NOTHING, blank=True, null=True)
learning_objective = models.ForeignKey(
LearningObjective, on_delete=models.DO_NOTHING, blank=True, null=True)
grade = models.CharField(
max_length=10, choices=GRADING_VALUE, blank=True, null=True)
note = models.TextField(blank=True, null=True)
debriefing = models.TextField(blank=True, null=True)
created_at = models.DateTimeField(auto_now_add=True)
updated_at = models.DateTimeField(auto_now=True)
def __str__(self):
return str(self.mission) + ' ' + str(self.log_entry)
class Meta:
verbose_name_plural = 'Mission Entries'
class MissionEntryStatus(models.Model):
mission = models.ForeignKey(
Mission, on_delete=models.PROTECT, null=True, blank=True)
student = models.ForeignKey(Student, on_delete=models.PROTECT)
is_completed = models.BooleanField(default=False)
is_failed = models.BooleanField(default=False)
created_at = models.DateTimeField(auto_now_add=True)
updated_at = models.DateTimeField(auto_now=True)
class StudentMission(models.Model):
mission = models.ForeignKey(Mission, on_delete=models.PROTECT)
student_training_course = models.ForeignKey(
StudentTrainingCourse, on_delete=models.PROTECT)
mission_status = models.ForeignKey(
MissionEntryStatus, on_delete=models.PROTECT, blank=True, null=True)
created_at = models.DateTimeField(auto_now_add=True)
updated_at = models.DateTimeField(auto_now=True)
class Meta:
ordering = ['mission__name']
def __str__(self):
return self.mission.name
class LogEntry(models.Model):
aircraft = models.ForeignKey(Aircraft, on_delete=models.DO_NOTHING)
adep = models.ForeignKey(
Aerodrome, on_delete=models.PROTECT, related_name='adep')
ades = models.ForeignKey(
Aerodrome, on_delete=models.PROTECT, related_name='ades')
date = models.DateField()
etd = models.TimeField()
ata = models.TimeField()
eet = models.TimeField()
function_type = models.ForeignKey(FunctionType, on_delete=models.PROTECT)
student = models.ForeignKey(
Student, on_delete=models.PROTECT, blank=True, null=True)
instructor = models.ForeignKey(
Instructor, on_delete=models.PROTECT, blank=True, null=True)
student_mission = models.ForeignKey(
'mission.StudentMission', on_delete=models.PROTECT, null=True, blank=True)
note = models.TextField(null=True, blank=True)
cross_country = models.BooleanField(default=False)
created_at = models.DateTimeField(auto_now_add=True)
updated_at = models.DateTimeField(auto_now=True)
views.py
def student_mission_list(request, pk):
student = Student.objects.get(id=pk)
student_training_course = StudentTrainingCourse.objects.filter(
student_id=student.id)
missions = StudentMission.objects.filter(
student_training_course_id__in=student_training_course)
mission_entry = MissionEntry.objects.filter(student_id=student)
log_entry = LogEntry.objects.filter(student_mission_id__in=missions)
print(log_entry)
context = {
'student': student,
'missions': missions,
'mission_entry': mission_entry,
}
return render(request, 'mission/student_mission_list.html', context)
In fact, what I need to do, is to obtain a single value for the log_entry. The problem is that, obviously, I am retrieving multiple values of log_entry. But I would like to get the single pk of the log_entry.
Any suggestion? Should I remodel the models.py file?
try this:
log_entry = LogEntry.objects.get(student_mission_id__in=missions)
print(log_entry.id)

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

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.

import m2m with Django-import-export failing

Data import using django-import-export is failing for m2m relationships.
The transaction doesn't generate any errors, however when trying to update an object's m2m relationship none of the updated values for m2m are being updated.
models.py
class Category(MPTTModel):
name = models.CharField(max_length=155, verbose_name=_('Category'))
code = models.CharField(max_length=255, verbose_name=_('Category Code'), help_text='primary key value for category', db_index=True)
categorytype = models.ForeignKey(ProductType, related_name='categories_for', verbose_name=_('Product type'), blank=True, null=True)
meta_description = models.TextField(verbose_name=_('Meta Description'))
meta_keywords = models.TextField(verbose_name=_('Meta Keywords'))
parent = TreeForeignKey('self', null=True, blank=True, related_name='children', db_index=True)
slug = models.SlugField(blank=True, verbose_name=_('URL alias'))
order = models.PositiveIntegerField()
class Product(models.Model):
reference = models.CharField(max_length=50, verbose_name=_('Reference'), db_index=True)
name = models.CharField(max_length=255, verbose_name=_('Product Name'))
description = models.TextField(blank=True, verbose_name=_('Product Description'))
specs = models.TextField(blank=True, verbose_name=_('Product Specifications'))
color_code = models.ForeignKey(ColorCode, verbose_name=_('Color Code'), related_name='colorcode_for')
color_web = models.CharField(max_length=7, verbose_name=_('Web Color'), db_index=True)
size = models.CharField(max_length=11, verbose_name=_('Product Size'))
price = models.IntegerField(verbose_name=_('Product Price'))
price_promo = models.IntegerField(blank=True, null=True, verbose_name=_('Product Promo Price'))
upc = models.CharField(max_length=155, verbose_name=_('UPC'))
stock = models.IntegerField(verbose_name=_('Product Stock'))
categories = models.ManyToManyField(Category, verbose_name=_('Estilo'), related_name='products')
in_stores = models.BooleanField(default=True, verbose_name=_('Product Availability'), db_index=True)
try_out = models.BooleanField(default=False, verbose_name=_('Try out Product'))
pub_date = models.DateTimeField(auto_now_add=True)
update = models.DateTimeField(auto_now=True)
slug = models.SlugField(default='', blank=True, verbose_name=_('URL alias'))
blog = models.URLField(blank=True, verbose_name=_('Blog mention link'))
parent_product = models.BooleanField(default=False, verbose_name=_('Main Product'), db_index=True)
main_product = models.ForeignKey('Product', blank=True, null=True, related_name='child_product')
active = models.BooleanField(default=True, verbose_name=_('Active'), db_index=True)
trends = models.ManyToManyField(Trends, verbose_name=_('Trends'), blank=True, related_name="trends")
photoshoot_id = models.CharField(max_length=255, verbose_name=_('Photoshoot ID'), blank=True)
new_arrival = models.BooleanField(default=False, db_index=True)
resources.py
class ProductResource(resources.ModelResource):
categories = fields.Field(widget=widgets.ManyToManyWidget(Category, separator="/"))
def export(self, queryset=None):
queryset = Product.objects.all()
headers = self.get_export_headers()
data = tablib.Dataset(headers=headers)
for obj in queryset.iterator():
data.append(self.export_resource(obj))
return data
class Meta:
model = Product
fields = ('categories', 'reference', 'name_es', 'name_en', 'description_es', 'description_en', 'specs_es', 'specs_en', 'color_code', 'color_web', 'size', 'price_es', 'price_en', 'price_promo_es', 'price_promo_en', 'upc', 'stock', 'in_stores', 'try_out', 'blog', 'active', 'photoshoot_id')
import_id_fields = ['upc']
skip_unchanged = True
Issue was fixed removing the skip_unchanged meta option, the skip_rowmethod in the ModelResource class is not reading the new value assigned in the .CSV

Categories

Resources