How to get all children of queryset in django? - python

I've a queryset result, say, animals, which has a list of animals. There are sub categories of animals and I want to get all the subcategories. i.e.
for single animal, I can use animal.categories which works. Now, I want to somehow do this:
categories = animals.categories
where animals is queryset. How can I achieve this?

There is no way without iterating over the query set, but you can use prefetch_related to speed things up:
all_animals = Animals.objects.prefetch_related('categories')
categories = [animal.categories.all() for animal in all_animals]

There are 2 options:
1) Following your question exactly, you can only do:
categories=[]
for aninmal in animals:
categories.extend(animal.categories.all())
2) However, I would run a new query with categories like that (I do not know your exact data model and wording, but I think you get the idea)
categories=Category.filter(animals__in=animals).all()

( Base: if animals.categories is giving a queryset that means categories has a many-to-one with animal. and default name (category_set) is changed with categories)
It seems to me like your main query should be a Category query instead of animals. Lets say you get animals like:
Animals.objects.filter(name__startswith='A')
You could get categories of this animals with following query
Category.objects.filter(animal__name__startswith='A')
You can also get animals with this query
Category.objects.filter(animal__name__startswith='A').select_related('category')
But I recommend to use seperate queries for categories and animals (will be more memmory efficent but will do two queries).
Note:If you are really using one-to-many You should consider changing it to many-to-many.

Related

Can I create Dynamic columns (and models) in django?

I want to create a database of dislike items, but depending on the category of item, it has different columns I'd like to show when all you're looking at is cars. In fact, I'd like the columns to be dynamic based on the category so we can easily an additional property to cars in the future, and have that column show up now too.
For example:
But when you filter on car or person, additional rows show up for filtering.
All the examples that I can find about using django models aren't giving me a very clear picture on how I might accomplish this behavior in a clean, simple web interface.
I would probably go for a model describing a "dislike criterion":
class DislikeElement(models.Model):
item = models.ForeignKey(Item) # Item is the model corresponding to your first table
field_name = models.CharField() # e.g. "Model", "Year born"...
value = models.CharField() # e.g. "Mustang", "1960"...
You would have quite a lot of flexibility in what data you can retrieve. For example, to get for a given item all the dislike elements, you would just have to do something like item.dislikeelements_set.all().
The only problem with this solution is that you would to store in value numbers, strings, dates... under the same data type. But maybe that's not an issue for you.

Django Model and Many-to-Many Relationships -- finding most similar objects

I'm running into an issue that I can't find an explanation for.
Given one object (in this case, an "Article"), I want to use another type of object (in this case, a "Category") to determine which other articles are most similar to article X, as measured by the number of categories they have in common. The relationship between Article and Category is Many-to-Many. The use case is to get a quick list of related Objects to present as links.
I know exactly how I would write the SQL by hand:
select
ac.article_id
from
Article_Category ac
where
ac.category_id in
(
select
category_id
from
Article_Category
where
article_id = 1 -- get all categories for article in question
)
and ac.article_id <> 1
group by
ac.article_id
order by
count(ac.category_id) desc, random() limit 5
What I'm struggling with is how to use the Django Model aggregation to match this logic and only run one query. I'd obv. prefer to do it within the framework if possible. Does anybody have pointers on this?
Adding this in now that I've found a way within the model framework to do this.
related_article_list = Article.objects.filter(category=self.category.all())\
.exclude(id=self.id)
related_article_ids = related_article_list.values('id')\
.annotate(count=models.Count('id'))\
.order_by('-count','?')
In the related_article_list part, other Article objects that match on 2 or more Categories will be included separate times. Thus, when using annotation to count them the number will be > 1 and they can be ordered that way.
I think the correct answer if you really want to filter articles on all category should look like this:
related_article_list = Article.objects.filter(category__in=self.category.all())\
.exclude(id=self.id)

Django: Most Efficient Way To Filter A Queryset Repeatedly

I have a model that looks something like this:
class Item(models.Model):
name = models.CharField()
type = models.CharField()
tags = models.models.ManyToManyField(Tags)
In order to render a given view, I have a view that presents a list of Items based on type. So in my view, there's a query like:
items = Item.objects.filter(type='type_a')
So that's easy and straight forward. Now I have an additional requirement for the view. In order to fulfill that requirement, I need to build a dictionary that relates Tags to Items. So the output i am looking for would be something like:
{
'tag1': [item1, item2, item5],
'tag2': [item1, item4],
'tag3': [item3, item5]
}
What would be the most efficient way to do this? Is there any way to do this without going to the database with a new query for each tag?
You can check prefetch_related it might help you:
This has a similar purpose to select_related, in that both are designed to stop the deluge of database queries that is caused by accessing related objects, but the strategy is quite different... prefetch_related, on the other hand, does a separate lookup for each relationship, and does the ‘joining’ in Python. This allows it to prefetch many-to-many and many-to-one objects, which cannot be done using select_related...
So in the end you will either do multiple queries or use prefetch_related and it will do some Python joins on the objects.
You might do something like this:
# This should require two database queries, one for the items
# and one for all the associated tags.
items = Item.objects.filter(type='type_a').prefetch_related('tags')
# Now massage the data into your desired data structure.
from collections import defaultdict
tag_dict = defaultdict(list)
for item in items:
# Thanks to prefetch_related this will not hit the database.
for tag in item.tags.all():
tag_dict[tag].append(item)

Django - Following ForeignKey relationships "backward" for entire QuerySet

is it possible to follow ForeignKey relationships backward for entire querySet?
i mean something like this:
x = table1.objects.select_related().filter(name='foo')
x.table2.all()
when table1 hase ForeignKey to table2.
in
https://docs.djangoproject.com/en/1.2/topics/db/queries/#following-relationships-backward
i can see that it works only with get() and not filter()
Thanks
You basically want to get QuerySet of different type from data you start with.
class Kid(models.Model):
mom = models.ForeignKey('Mom')
name = models.CharField…
class Mom(models.Model):
name = models.CharField…
Let's say you want to get all moms having any son named Johnny.
Mom.objects.filter(kid__name='Johnny')
Let's say you want to get all kids of any Lucy.
Kid.objects.filter(mom__name='Lucy')
You should be able to use something like:
for y in x:
y.table2.all()
But you could also use get() for a list of the unique values (which will be id, unless you have a different specified), after finding them using a query.
So,
x = table1.objects.select_related().filter(name='foo')
for y in x:
z=table1.objects.select_related().get(y.id)
z.table2.all()
Should also work.
You can also use values() to fetch specific values of a foreign key reference. With values the select query on the DB will be reduced to fetch only those values and the appropriate joins will be done.
To re-use the example from Krzysztof Szularz:
jonny_moms = Kid.objects.filter(name='Jonny').values('mom__id', 'mom__name').distinct()
This will return a dictionary of Mom attributes by using the Kid QueryManager.

Getting Unique Foreign Keys in Django?

Suppose my model looks like this:
class Farm(models.Model):
name = ...
class Tree(models.Model):
farm = models.ForeignKey(Farm)
...and I get a QuerySet of Tree objects. How do I determine what farms are represented in that QuerySet?
http://docs.djangoproject.com/en/dev/ref/models/querysets/#in
Farm.objects.filter(tree__in=TreeQuerySet)
There might be a better way to do it with the Django ORM and keep it lazy but you can get what you want with regular python (off the top of my head):
>>> set([ t.farm for t in qs ])
Here is a way to have the database do the work for you:
farms = qs.values_list('farm', flat=True).distinct()
#values_list() is new in Django 1.0
return value should evaluate to something like:
(<Farm instance 1>, <Farm instance5>)
were farms will be those that have trees in that particular query set.
For all farms that have trees, use qs = Tree.objects
Keep in mind that if you add order_by('some_other_column') then distinct will apply to the distinct combinations of 'farm' and 'some_other_column', because other column will also be in the sql query for ordering. I think it's a limitation (not an intended feature) in the api, it's described in the documentation.

Categories

Resources