[Answer]-Django create profile or page for object

1👍

Yes, you are taking a right approach. Usually when you want to have a decoupled entity and then later if you want to associate attributes with it (e.g. profile to a user), OneToOneField is very useful.

As far as connecting, since these are two separate tables, there is no really good way of merging these. However since you are using related_name parameter, even though models are different, you can easily access attributes of the other model by:

venue = Venue.objects.get(...)
venue.name             <- Venue attribute
venue.venueProfile.foo <- VenueProfile attribute

One down side of this approach is that there are database queries involved. To make this more efficient, you can do either one of these approaches. The first approach however is more efficient since for that, Django will use SQL join which is faster to “Python’s” joins.

profile = VenueProfile.objects.filter(...).select_related('venue')[0]
venue = profile.venue <- no extra query

or this method for here Django will do the join in Python so slower:

venue = Venue.objects.filter(...).prefetch_related('venueProfile')[0]

At this point, these are just regular objects so you can easily pass them to template. The following is a simple view, urlconfig and template example:

def all_venues(request):
    # note that querying profiles...
    venues = VenueProfile.objects.all().select_related('venue')
    return render_to_response('template.html', {'venues':venues})

def venue(request, venue_id):
    venue = VenueProfile.objects.filter(venue__pk=venue_id).select_related('venue')
    if len(venue) == 1:
        venue = venue[0]
    else:
        raise Http404
    ...

urlconfig:

url(r'^venue/all/$', 'all_venues', name='all_venues'),
url(r'^venue/(?P<venue_id>\d+)/$', 'venue', name='venue'),

and template

{% load url from future %}
{% for venue_profile in venues %}
    {% with venue=venue_profile.venue profile=venue_profile %}
        <ul>
            <li>
                <a href="{% url 'venue' venue_id=venue.pk %}">
                    {{ venue.name }}</a><br>
                <img href="{{ venue.image.url }}"><br>
                {{ profile.foo }}
            </li>
        </ul>
    {% endwith %}
{% empty %}
    No venues
{% endfor %}

Leave a comment