In rest api view I need to have 2 objects. For example:
class Foo(models.Model):
....
class Bar(models.Model):
....
What is correct way to get them? I mean how should I configure urls? I think this is not really good practice: url(r'^foo/(?P<pk>\d+)/bar/(?P<pk>\d+)/$', FooBarView.as_view())
Or: url(r'^foobar/$', FooBarView.as_view())
and then pass parameters: ?foo=1&bar=2
.
I think it is more like a design problem.
Which one is better? I will say it depends on what is the relationship between model foo and model bar.
If you get model Class and model student, and you want to get student info and base on which class and relative student_number, like each class will have a student no.1.
you can go:
url(r'^class/(?P<class_pk>\d+)/student/(?P<student_pk>\d+)/$')
If you want to get both model information, but you want put them into a statistic table,
you can go:
url(r'^statistic/$')
then pass parameters like:
?class=1&student=2
These are just simple examples, there should be other cases, and you should use other way to design your URL API.
For django >= 1.5 You could pass parameters to class view doing somethin like this:
class Foo(TemplateView):
template_name = "yourtemplatesdir/template.html"
# Set any other attributes here
# dispatch is called when the class instance loads
def dispatch(self, request, *args, **kwargs):
self.id = kwargs.get('foo_id', "other_def_id")
self.barid = kwargs.get('bar_id', "other_def_id")
# depending on your definition, this class might be different
class Bar(TemplateView):
template_name = "yourtemplatesdir/template.html"
# Set any other attributes here
# this method might not be necessary
# dispatch is called when the class instance loads
def dispatch(self, request, *args, **kwargs):
self.id = kwargs.get('bar_id', "other_def_id")
In your url conf something like:
from .views import FooBar
urlpatterns = patterns('',
url(
regex=r'^(?P<foo_id>\d+)/(?P<bar_id>\d+)/$'
view=FooBar.as_view(),
name='viewname'
),
)
Then, in your template view for FooBar, you could do:
{{ view.id }}
{{ view.barid }}
I hope it helps, it could be more detailed if you provide further information about the object information needed in your 'action'.