In a model field (and subsequently in modelforms, modelform field and widgets) what is "rel"

31 views
Skip to first unread message

Timmy O'Mahony

unread,
Oct 19, 2011, 1:21:10 PM10/19/11
to django...@googlegroups.com
I am trying to use a 3rd party form field and custom widget in my own model form and I am having trouble understanding what the "rel" attribute is used for.

for example:

class SomeFormField(forms.ModelChoiceField):
def __init__(self, rel, queryset, to_field_name, *args, **kwargs):
...

I see it originates here:

Andre Terra

unread,
Oct 19, 2011, 1:58:10 PM10/19/11
to django...@googlegroups.com
Hello, Timmy

"rel" is the related manager object that will be used in specific fields, namely those that refer to relationships to other table. These relationships are handled by objects in django.db.models.fields.related[1].

For example, take User and Group from django.contrib.auth.models. Assuming you have a User named Foo and a Group named Bar, this is what you would see in a Python shell:

>>> User.objects.all()[0]

<User: Foo>

>>> User.groups

<django.db.models.fields.related.ReverseManyRelatedObjectsDescriptor object at 0x01598770>

>>> Group.user_set

<django.db.models.fields.related.ManyRelatedObjectsDescriptor object at 0x01598250>

>>> Group.objects.all()[0]

<Group: Bar>

>>> Group.objects.all()[0].user_set

<django.db.models.fields.related.ManyRelatedManager object at 0x017E3C30>


The User model has a ForeignKey field that points to Group, so in return, the Group class gets a ManyRelatedObjectDescriptor which allows each instance of Group to have a ManyRelatedManager, accessible through somegroup.user_set.

>>> Group.objects.all()[0].user_set.all()

[<User: Foo>]


As you can see, this user_set object (a ManyRelatedManager) is an object manager which has an API that is similar to that of User.objects, aside from some special attributes and characteristics.


Beware that this is deep ORM stuff and the code can be hard to grasp at first. Personally, I haven't read through it more than twice. Let us know if you have any more doubts!


Cheers,
AT

[1] https://code.djangoproject.com/browser/django/trunk/django/db/models/fields/related.py

--
You received this message because you are subscribed to the Google Groups "Django users" group.
To view this discussion on the web visit https://groups.google.com/d/msg/django-users/-/4rXHWwhzCPQJ.
To post to this group, send email to django...@googlegroups.com.
To unsubscribe from this group, send email to django-users...@googlegroups.com.
For more options, visit this group at http://groups.google.com/group/django-users?hl=en.

Timmy O'Mahony

unread,
Oct 19, 2011, 8:05:10 PM10/19/11
to django...@googlegroups.com
Wow, thanks for the great reply. It makes sense that it's the related object manager. I have everything working now so thank you very much again!
Reply all
Reply to author
Forward
0 new messages