please I need your help how to reduce the database call when using ModelChoiceField as it requires a queryset and I have to use it three times separately with a model that is recursively foreign key on itself, the code is below:
ModelForm code in the init function
self.fields['category'] = forms.ModelChoiceField(queryset=queryset)
self.fields['super_category'] = forms.ModelChoiceField(queryset=)
self.fields['product_type'] = forms.ModelChoiceField(queryset=)
the model class:
class Category(ProjectBaseModel, AuditLogMixin):
parent_id = models.ForeignKey('self', related_name='children', blank=True, null=True, on_delete=models.CASCADE,verbose_name=_('Parent'))
what i tried to do is collect all ids of the desired categories in array and make only one filter queryset with them like the following:
category = auction.category
super_category = category.parent_id
product_type = super_category.parent_id
ids= [category.id,super_category.id,product_type.id]
queryset = Category.objects.filter(id__in=ids)
How to proceed with that solution
Related
models.py
class products(models.Model):
name = models.CharField(max_length=100)
sku = models.CharField(max_length=50)
vendor = models.CharField(max_length=50)
brand = models.CharField(max_length=50)
price = models.FloatField()
product_status = models.BooleanField()
quantity = models.IntegerField()
def __str__(self):
return self.name
# categories
class categories(models.Model):
category_name = models.CharField(max_length=50)
parent_id = models.IntegerField()
# product categories
class product_categories(models.Model):
product = models.ForeignKey(products, on_delete=models.CASCADE)
category = models.ForeignKey(categories, on_delete=models.CASCADE)
def __str__(self):
return self.category
I can access 'category' table data(inside django shell) using
data = products.objects.all()
data.values('product_categories__category__category_name')
output: <QuerySet [{'product_categories__category__category_name': 'xxxx'}}]>
If I put this(inside django shell)
data.product_categories.category
output: 'QuerySet' object has no attribute 'product_categories'
How do I get a queryset(can be passed to html) which includes data from "categories" table along with the data of "products" table
There are a couple of issues happening here. First, data is a queryset, which is kind of like a list of objects, even though here there's just one object in the list. What you want is to get an attribute off of the item in the list, so you need something like a data.first() to get to that object before you start dotting into its attributes.
Secondly, the way Django handles reverse FK relationships requires that you refer to the FK by the standard name of, in your case, product_categories_set, OR you set your own related_name attribute on the FK. Something like:
# product categories
class product_categories(models.Model):
product = models.ForeignKey(products, on_delete=models.CASCADE, related_name='product_categories')
category = models.ForeignKey(categories, on_delete=models.CASCADE, related_name='product_categories')
def __str__(self):
return self.category
so that you can refer to your product_categories model from both the product and categories using just data.product_categories.
Thirdly, when accessing a reverse FK relationship, just like in point (1) above, you will get a related manager, from which you can get a queryset of items. Thus, to get the category name, you need to indicate which item you want the category name for. Assuming it's just the first item for everything, it would look something like:
data = products.objects.all()
product_category = data.product_categories.all()
category_name = product_category.category.category_name
Of course once you have more data, you'll not always want to just pick the first item, so you'll need to add filtering logic into the query to make sure you get the item you're looking for.
ETA, I do agree with the comment by Jorge above - a MTM would make this a bit simpler and would, in essence, create your product_categories table for you.
i am using django(3.1.5). and i am trying to get parent model to child model by filter query
i have model like -
class Product(models.Model):
product_name = models.CharField(max_length=255, unique=True)
is_feature = models.BooleanField(default=False)
is_approved = models.BooleanField(default=False)
created_at = models.DateTimeField(auto_now_add=True)
class ProductGalleryImage(models.Model):
product = models.ForeignKey(Product, on_delete=models.CASCADE)
product_gallery_image = models.FileField(upload_to='path')
is_feature = models.BooleanField(default=False)
i am getting data from SELECT * FROM products_product AS pp INNER JOIN products_productgalleryimage AS ppgi ON ppgi.product_id = pp.id WHERE ppgi.is_feature=1 AND pp.is_feature=1 AND is_approved=1 ORDER BY pp.created_at LIMIT 4 mysql query.
so how can i get data like this query in django filter query
Firstly you can add related_name to ProductGalleryImage for better query support like this
product = models.ForeignKey(Product, on_delete=models.CASCADE, related_name='product_images')
Then your query should be like this
products=Product.objects.filter(is_approved=True, is_feature=True, product_images__is_feature=True).order_by('created_at')[:4]
You can simply loop over the other related model like so:
for product_gallery_image in product_instance.productgalleryimage_set.all():
print(product_gallery_image.product_gallery_image)
The productgalleryimage_set here is simply the related model name in lowercase with _set appended. You can change this by setting the related_name attribute on the foreign key.
Note: This will perform a query to fetch each of the product_gallery_image objects of some product instance.
If you want to get the first object only:
product_gallery_image = product_instance.productgalleryimage_set.first()
If you want to perform a join as in your example which will perform only one query you can use select_related (this will only work in forward direction for reverse direction look at prefetch_related):
product_gallery_images = ProductGalleryImage.objects.all().select_related('product')
for product_gallery_image in product_gallery_images:
print(product_gallery_image.product.product_name)
print(product_gallery_image.product_gallery_image)
I have a Django model with a GenericForeignKey, and several other models pointing to it through GenericRelation:
class InventoryAction(CustomModel):
action_content_type = models.ForeignKey(ContentType, on_delete=models.PROTECT,limit_choices_to={'model__in': ('inventoryinput', 'inventorytransfer', 'inventoryadjustment', 'physicalinventory', 'requisition', 'sale', 'inventorysalecancellation', 'inventorystockinit')}, related_name='inventory_actions', verbose_name=_("Tipo de Acción"))
action_object_id = models.PositiveIntegerField(verbose_name=_("ID de la acción"))
action_object = GenericForeignKey('action_content_type', 'action_object_id')
timestamp = models.DateTimeField(auto_now=True, verbose_name=_("Fecha y hora"))
class InventoryStockInit(CustomModel):
repository = models.ForeignKey(Repository, on_delete=models.PROTECT, related_name='stock_init', verbose_name=_("Almacén"))
timestamp = models.DateTimeField(auto_now=True, verbose_name=_("Fecha y Hora"))
comments = models.TextField(null=True, blank=True, verbose_name=_("Comentarios"))
inventory_action = GenericRelation(InventoryAction, content_type_field='action_content_type', object_id_field='action_object_id')
class InventoryInput(CustomModel):
repository = models.ForeignKey(Repository, on_delete=models.PROTECT, related_name='inputs', verbose_name=_("Almacén"))
reference = models.ForeignKey(InventoryAction, null=True, blank=True, on_delete=models.PROTECT, limit_choices_to=Q(action_content_type__model__in=['inventorytransfer', ]), related_name='referenced_by', verbose_name=_("Referencia"))
inventory_action = GenericRelation(InventoryAction, content_type_field='action_content_type', object_id_field='action_object_id')
And I have a Django Rest Framework viewset that attempts to get all related records from the GenericForeignKey:
class InventoryActionForListViewSet(viewsets.ViewSet):
permission_classes = (permissions.IsAuthenticated,)
def list(self, request):
self.repository = request.query_params['repository']
inventory_actions = models.InventoryAction.objects.filter(inventory_action__repository_id=self.repository).order_by('-timestamp')
inventory_actions_to_return = serializers.InventoryActionForListSerializer(inventory_actions, many=True)
return Response(inventory_actions_to_return)
The problem is that the view raises the following exception:
django.core.exceptions.FieldError: Cannot resolve keyword 'inventory_action' into field. Choices are: action_content_type, action_content_type_id, action_object, action_object_id, batch, id, products, referenced_by, referenced_by_input_or_output, referenced_by_output, timestamp
I can see that the GenericRelation is not being recognized. how can I execute the query I want, using generic relationships?
inventory_action is a field on your InventoryStockInit and InventoryInput models - you can't expect it to be a field in your InventoryAction model.
With the relation you defined, each of your InventoryAction objects can be related to a single object in one of he models stated in limit_choices_to. There is only one object related to a single InventoryAction. You can access it by accessing action object, for example:
inventory_action = InventoryAction.objects.first()
inventory_action.action_object # this will be a single object of one of the models in limit_choices_to.
Your InventoryInput model on the other hand can be pointed by multiple inventory actions. To see which inventory actions are pointing to a particular InventoryInput object, you can do:
inventory_input = InventoryInput.objects.first()
inventory_input.inventory_action.all()
As you can see, inventory_action is a manager of all related objects, it would be better to call it inventory_actions (plural). I think what you might be trying to achieve is a reverse relation (single InventoryAction object referenced by multiple objects of other models).
My app has a model "OptimizationResult", where I store results from mathmatical optimization. The optimization distributes timeslots over projects. I need to indicate whether the current results is different from a recent result, based on a set of attributes (in particularly not the primary key)
The attribute optimization_run is a coutner for different runs
Project is a ForeignKey to the project.
By overwriting the __hash__ and __eq__ functions on the model I can compare the different instances by
OptimizationResults.objects.filter(proj = 1).filter(optimization_run =1).first() == OptimizationResults.objects.filter(proj = 1).filter(optimization_run = 2).first()
. But as I understand __eq__ and __hash__ are not available on the database.
How would I annotate the results accordingly? Something like
OptimizationResults.objects.filter(optimization_run = 2).annotate(same_as_before = Case(When(),default=False))
Edit
Added .first() to the code, to ensure that there is only one element.
class OptimizationResult(models.Model):
project = models.ForeignKey(project, on_delete=models.CASCADE)
request_weight = models.IntegerField()
periods_to_plan = models.IntegerField()
unscheduled_periods = models.IntegerField()
scheduled_periods = models.IntegerField()
start = models.DateField(null=True, blank=True, default=None)
end = models.DateField(null=True, blank=True, default=None)
pub_date = models.DateTimeField('Erstellungsdatum', auto_now_add=True, editable=False)
optimization_run= models.ForeignKey(OptimizationRun, on_delete=models.CASCADE)
I'd like to compore different entries on the basis of start and end.
Edit 2
My fruitless attempt with Subquery:
old = OptimizationResult.objects.filter(project=OuterRef('pk')).filter(optimization_run=19)
newest = OptimizationResult.objects.filter(project=OuterRef('pk')).filter(optimization_run=21)
Project.objects.annotate(changed = Subquery(newest.values('start')[:1])== Subquery(old.values('start')[:1]))
results in TypeError: QuerySet.annotate() received non-expression(s): False
We can use a subquery here, to make an annotation:
from django.db.models import Exists, OuterRef, Subquery, Q
to_exclude = {'pk', 'id', 'project', 'project_id', 'optimization_run', 'optimization_run_id'}
subquery = OptimizationResult.objects.filter(
project_id=OuterRef('project_id')
optimization_run=1,
**{f.name: OuterRef(f.name)
for f in OptimizationResult._meta.get_fields()
if f.name not in to_exclude
}
)
OptimizationResult.objects.filter(
optimization_run=2
).annotate(
are_same=Exist(subquery)
)
Here we will thus annotate all the OptimizationResults with an optimization_run=2, with an extra attribute .are_same that checks if there exists an OptimizationResult object for optimization_run=1 and for the same project_id, where all fields are the same, except the ones in the to_exclude set.
I'm trying to replace a field in an intermediate table with a generic field. Using Django 1.6, MariaDB/MySQL.
I have a class (PermissionGroup) that links a resource to a group. Works fine. However I have several other tables that are similar - linking some id to a group id.
I thought I could replace these tables with one table that uses a generic foreign key, along with the group id. However this does not validate.
Here's the original, which works:
# core/models.py
class PermissionGroup(models.Model):
resource = models.ForeignKey('core.Resource')
group = models.ForeignKey('auth.Group')
class Resource(models.Model):
groups = models.ManyToManyField('auth.Group', through='core.PermissionGroup')
# auth/models.py
class Group(models.Model):
name = models.CharField(max_length=80, unique=True)
Now, trying to change the PermissionGroup to use a GenericForeignKey:
# core/models.py
class PermissionGroup(models.Model):
content_type = models.ForeignKey('contenttypes.ContentType')
object_id = models.PositiveIntegerField()
content_object = generic.GenericForeignKey()
group = models.ForeignKey('auth.Group')
class Resource(models.Model):
groups = models.ManyToManyField('auth.Group', through='core.PermissionGroup')
# auth/models.py
class Group(models.Model):
name = models.CharField(max_length=80, unique=True)
The django model validation now fails with:
core.resource: 'groups' is a manually-defined m2m relation through model PermissionGroup, which does not have foreign keys to Group and Resource
Is this simply not possible, or is another means to accomplish this?