I have a field in my Django model defined as:
def get_field(**kwargs):
kwargs.setdefault('related_name', '+')
return models.ManyToManyField('app.MyOtherModel', **kwargs)
class MyModel(models.Model):
MY_FIELD = 'A label for my field'
my_field = get_field() # wrote function to DRY creation of fields
But whenever I try to add something to the field, it doesn't work:
foo = MyOtherModel.objects.create(...)
m = MyModel.objects.get(...)
m.my_field.add(foo)
m.my_field.all() # returns []
Doing some digging into Django source code, the ManyRelatedManager.add()
function (in django/db/models/fields/related.py
) works correctly, with self.through.objects.all()
returning the right object at the end of the function, but self.all()
doesn't, leading me to think the problem is in get_queryset()
:
# printing self.through.objects.all() @ related.py:978
[<MyModel_myothermodel: MyModel_myothermodel object>]
# printing self.all() @ related.py:978
[]
Is the problem in the fact that I have both MY_FIELD
and my_field
defined in MyModel
? Or maybe in how I generate the ManyToManyField
? Or is there some other issue?
UPDATE: The issue is in related.py
in the get_queryset
function. self.core_filters
is set to {'+__year': 2015}
, however, when I query qs.values('+__year')
, I get {'+__year': None}
. (year
is another field in the model)
my_field
? Wouldn't a normal m2m field does your work?MY_FIELD_LABEL
instead? // Wang- the weird setup is because I have around 50 ManyToMany fields, and I'd like to be able to access the names of the fields from the class level.