I have 3 models:
class Model1(models.Model):
name = models.CharField(max_length=30)
class Model2(models.Model):
model1 = models.ForeignKey(Model1)
class Model3(models.Model):
model2 = models.OneToOneField(Model2)
value = models.IntegerField()
I want to get the max among Model1#model2_set#model3.value. How can I do that?
class Model1(models.Model):
name = models.CharField(max_length=30)
def model2_max_value(self):
model2_set.
# for each item in model2_set
# get model2_set_item.model3.value
# and find max among them
I thought I could apply aggregate(Max) here but couldn't find the way to do it.
Something like this should work:
max_value = Model3.objects.filter(model2__model1=self).aggregate(Max('value'))
Related
Filter Model_A with Model_B
Return Items of Model_A
class Model_A(models.Model):
name = models.CharField()
age = models.CharField()
class Model_B(models.Model):
name = models.CharField()
location = models.CharField()
def some_filter_function():
return [list of Model_A items based on Model_B.name]
considering you can't change the Model to use foreignkey, you can try something like this:
my_items = []
names = Model_b.objects.all()
for name in names:
name_b = name.name
model_a = Model_a.objects.filter(name = name)
for item in model_a:
my_items.append(item)
I agree with #William Van Onsam.
If you define your Model_A like
class Model_B(models.Model):
name = models.CharField()
location = models.CharField()
class Model_A(models.Model):
name = models.CharField()
age = models.CharField()
b = models.ForeignKey(Model_B, on_delete=models.CASCADE)
# NOTE you need to declare Model_B prior to Model_A,
# and then you can use Model_B as a parameter here.
Then you can do
def some_filter_function():
b = get_model_b()
return Model_A.objects.filter(name=b.name)
in your view function.
Consider the following approach.
def some_filter_function():
queryset = None
if Model_B.objects.filter(name="Jorge").exists()
queryset = Model_A.objects.all()
return queryset
I have four models as follows:
class modelA(models.Model):
name = models.CharField(...)
class modelB(models.Model):
date = models.DateTimeField(...)
A = models.ForeignKey(modelA, ...)
class modelC(models.Model):
email = models.CharField(...)
B = models.ForeignKey(modelB, ...)
class modelD(models.Model):
uid = models.CharField(...)
C = models.ForeignKey(modelC)
Given modelA element id, I have to filter modelD elements based on that id. But I am not sure about how to do that.
I appreciate any ideas!
modalD.objects.filter(C__B__A__name ='name')
when you use double underscore you filter the related Inheritance modal
Environment is Python and Django3
I want to make api which retrieve the data from multiple model class.
I have models like this , each CountryStat has Country.
class Country(models.Model):
code = models.CharField(max_length=3,unique=True)
name = models.CharField(max_length=50)
class CountryStat((models.Model):
country = models.ForeignKey(Country, on_delete=models.CASCADE,null=True)
date = models.DateField(null=True,blank =True)
stat = models.IntegerField()
Now I want to get the latest Coutry Stat for each Country.
So I made the serializer for Country
class CountrySerializer(serializers.ModelSerializer):
latest_stat = serializers.SerializerMethodField()
class Meta:
model = Country
fields = ('id','code','latest_stat')
def get_latest_stat(self,obj):
# how can I get the latest stat from CountryStat model ????
Is this the correct idea or how can I make it??
You should define a custom latest_stat attribute on your model:
class Country(models.Model):
code = models.CharField(max_length=3,unique=True)
name = models.CharField(max_length=50)
def latest_stat(self):
return self.countrystat_set.order_by('-date').first()
I have model classes:
class Product(models.Model):
category = models.ForeignKey(Category)
name = models.CharField(max_length=90)
...
class Category(models.Model):
name = models.CharField(max_length=90)
description = models.CharField(max_length=2000)
properies = models.ManyToManyField(Property)
...
#property type, ex: 'weight', 'length'
class Property(models.Model):
...
#value for every product
class PropertyValue(models.Model):
product = models.ForeignKey(Product)
property = models.ForeignKey(Property)
...
and I need custom product/add/ page, having PropertyValue forms set depends on chosen category.
I've made a method getting PropertyValue list by category_id in ModelAdmin class, but how can I call it in runtime when chosen category changes? Is it possible in django?
What do you mean when you said in runtime. If those categories change, the new records will apear every time you load the add pages.
Did you do yor form class? Kind of:
class PropertyValueForm(forms.Form):
product = forms.ModelChoiceField(queryset=Product.objects.all())
property = forms.ModelChoiceField(queryset=Property.objects.all())
Or:
def getProduct():
# DO YOUR STUFF
return product_list
class PropertyValueForm(forms.Form):
product = forms.ChoiceField(choices=get_my_choices())
I'm trying to return a queryset of all items in a Category where items can occur in multiple categories. The relevant model declarations are below along with one of many attempts that did not work. Is there a way to do this using Django's built-in intermediate table functionality without having to explicitly declare a model for the intermediary table?
class Category(models.Model):
parent = models.ForeignKey('self',null=True,blank=True)
name = models.CharField(max_length=150,null=True)
description = models.CharField(max_length=255,null=True,blank=True)
def items(self):
curr_category = Category.objects.filter(pk=self.id)
items_in_category = curr_category.item__categories_set.all().values('item_id')
return Item.objects.filter(pk__in=items_in_category)
def __unicode__(self):
return self.name
class Item(models.Model):
name = models.TextField(null=True,blank=True)
price = models.DecimalField(max_digits=10, decimal_places=2,null=True,blank=True)
categories = models.ManyToManyField(Category,null=True)
One way you could do this is with a custom models.Manager on your Item model. This is ideal, IMHO, because this logic doesn't really belong in your Category model. What if you want categories for things besides Item's? Then you'd have to implement more retrieval methods on Category, bloating it.
class Category(models.Model):
parent = models.ForeignKey('self',null=True,blank=True)
name = models.CharField(max_length=150,null=True)
description = models.CharField(max_length=255,null=True,blank=True)
def __unicode__(self):
return self.name
class ItemManager(models.Manager):
def get_for_category(self, category):
return self.filter(categories=category)
class Item(models.Model):
name = models.TextField(null=True,blank=True)
price = models.DecimalField(max_digits=10, decimal_places=2,null=True,blank=True)
categories = models.ManyToManyField(Category,null=True)
objects = ItemManager()
Then call this using:
items = Item.objects.get_for_category(category_instance)
If you really want to do it in a Category method, then why not:
class Category(models.Model):
def items(self):
# probably need to import Item model here in order to avoid
# circular import reference
from myapp.models import Item
return Item.objects.filter(categories__id=self.id)