Q:

What is the relationship between django cms and custom plugin models?

I've been working with django cms recently for the first time and I've created a gallery plugin for uploading images.
It's quite a simple plugin, using a ImageGalleryPlugin model which inherits from CMSPluginBase and then an Image model which has a ForeignKey to the gallery.
The gallery plugin is attached to pages using a placeholder and then to view the images within a gallery I have created an apphook to link the plugin template to a view similar to;
def detail(request, page_id=None, gallery_id=None):
    """
    View to display all the images in a chosen gallery
    and also provide links to the other galleries from the page
    """
    gallery = get_object_or_404(ImageGalleryPlugin, pk=gallery_id)
    # Then get all the other galleries to allow linking to those
    # from within a gallery
    more_galleries = ImageGalleryPlugin.objects.all().exclude(pk=gallery.id)
    images = gallery.images_set.all()

    context = RequestContext(request.context, {
        'images': images,
        'gallery': gallery,
        'more_galleries': more_galleries
    })
    return render_to_template('gallery-page.html', context)

Now the problem I have with this method is when you publish a page in CMS it duplicates all of the ImageGalleryPlugin objects on that page, so when I'm viewing the images, I've got twice as many links to the other galleries because the query collects the duplicate objects.
I haven't been able to properly understand this behaviour from the docs but I think the CMS is keeping the original objects which you've created and then creating the duplicates as 'live' versions of the galleries to display to users.
Where in CMS does this happen and where are the ID's of my ImageGalleryPlugin objects stored so that I can only collect the right ones in this view instead of collecting all objects?

A:

I've finally solved my own problem.
The association between my CMSPlugin object and the Page is myobj.placeholder.page so the solution to my filtering is;
    # Get the ImageGalleryPlugin object
    gallery = get_object_or_404(ImageGalleryPlugin, pk=gallery_id)

    # Get all other ImageGalleryPlugin objects
    galleries = ImageGalleryPlugin.objects.all().exclude(pk=gallery.id)

    # Get all the images in the chosen gallery
    images = gallery.image_field.images

    # Filter the list of other galleries so that we don't get galleries
    # attached to other pages.
    more_galleries = [
        g for g in galleries if unicode(g.placeholder.page.id) == page_id
    ]

