Django filter manytomany results - python

Say that I have a many to many relationship field in my model, what I'm trying to do is get all the related entities if the field in the entity is equivalent to MAMMAL. I'm currently doing this in a list comprehension but wondering if there's a more elegant solution that django models provide.
[related_entity for related_entity in related_entity.related_entities.all() if
related_entity.entity_type.entity_type_label == 'MAMMAL']

Based on Django documentation(https://docs.djangoproject.com/en/1.9/topics/db/examples/many_to_many/), you could use:
entity.objects.filter(related_entity__entity_type__entity_type_label == 'MAMMAL')

A many-to-many field gives you a manager, just like the standard Model.objects() one, and you can filter it in exactly the same way:
related_entity.filter(entity_type__entity_type_label="MAMMAL")

Related

How do I get a specific field in Django query?

I'm trying to query only a specific field in Django model. After some searching, I figured out that I need to use only(). However I need to use filter(authuser=request.user) as well. How do I make it possible? Thank you.
You can chain refinements together, since that returns another QuerySet.
Lets say the model is User, and the field is name.
User.objects.filter(authuser=request.user) \
.only('name')
You can pass other fields to .only(), they just need to be comma separated.

Django CharField add to choices from front-end

Problem Description
Suppose I have a model with a CharField that has choices as follows:
class MyModelWithChoice(models.Model):
FIELD1_CHOICES = (('1', 'One'),)
field1 = models.CharField(max_lenth=32, choices=FIELD1_CHOICES)
Is there a way to add to these choices from the front end?
Preventing the problem
I know that the problem can be prevented by creating another model and using a ForeignKey for field1, which works just fine.
Reason I'm trying to find another way
The reason I'm trying to avoid creating a new model is because it doesn't really carry any more information. If it contained further information about the choice, I wouldn't have a problem, but it seems like too much overhead to create a table in the db just for the choices
I think you must use django forms then you can use django forms in your fron-end
See this documentation from django offical website

Django count all occurances of one model in many other models

I'm using django and I have model names Tags.
It is used in 15 different models accros my entire application as ManyToManyField.
I need to get a len / count of all occurances of specific tag.
How am I suposed to do that ? Do I have to use Aggregate / annotate ? Select related ? Or something completelty different. Ofcourse using forloops is not an opiton.
If you want be able to query in one request how many items are related to a Tag if they are different Django model, you should use the contenttypes framework provided by Django and not define Tags as a ManyToMany field.
Samples in the documentation is exactly what you want.
https://docs.djangoproject.com/en/1.8/ref/contrib/contenttypes/#generic-relations
https://docs.djangoproject.com/en/1.8/ref/contrib/contenttypes/#reverse-generic-relations

Django searchable drop down for ForeignKey widget

in my Django model I have a m2m relation with an intermediate model that contain the two foreign keys of the respective two models.
My problems is that, the first model may have many entries and when I associate it with other model I have a too large drop down widget in the admin.
The default ManyToManyField widget (with filter_horizontal set) may be ok, but it is compatible only with m2m relations....
Is there a solution (even 3rd parts) for the ForeignKeyFields?
Any suggestions?
Edit:
For the other users, I've solved my problem using django-selectable
http://django-selectable.readthedocs.org/en/v0.8.X/index.html
The 3rd party component Django Ajax Selects does exactly what you are looking for.
I played around with django-selectable as well, but found django-autocomplete-light (https://github.com/yourlabs/django-autocomplete-light‎) easier to use and more flexible for what I wanted to achieve.
Perhaps it can be useful to you as well.

Django model iterate fields

how can I iterate and retrieve all fields of a django model?
I know that foo.item._meta.get_all_field_names() brings me all field names.
How can I access those fields (incl. their actual values) on a model instance? (Except the normal notation foo.fieldname).
I need this in order to build a custom output for my model including its manyTomany relations.
Any ideas?
How about:
getattr(foo.__class__, <field_name>)
This should give you the field object, rather than the value in the given model instance. If you want the value of the field in the given model insance you can call it like this:
getattr(foo, <field_name>)
This looks ugly but it will work:
for each in model_instance._meta.fields:
print each.value_from_object(model_instance)
That said, I have another suggestion. Given that your requirement is to
to build a custom output for my model including its manyTomany relations.
how about serializing the instance to a suitable format (XML/JSON) and then working on that? this avoids any dependency on _meta or any of the internal methods (which can possibly change).

Categories

Resources