0

I am writing a reusable Carousel app. It needs to refer to a model in the main project, so I have used a generic foreign key. I have something like this in the reusable app:

from django.db import models
from django.contrib.contenttypes.models import ContentType
from django.contrib.contenttypes import generic

class MyCarousel(models.Model):
    content_type = models.ForeignKey(ContentType)
    object_id = models.PositiveIntegerField()
    content_group = generic.GenericForeignKey('content_type', 'object_id')
    ...

Now I would like the project to be able to limit the content_type's type. If I was doing this in the above class declaration I could rewrite the content_type line as follows:

    content_type = models.ForeignKey(ContentType, limit_choices_to=models.Q(app_label = 'myapp', model = 'mymodel'))

But the reusable app doesn't know which model it will be used with, so I want to limit the choices later, in the project.

Can this be done? E.g. like this pseudo-code:

import my_carousel.models
my_carousel.models.MyCarousel.content_type.limit_choices_to = models.Q(app_label = 'myapp', model = 'mymodel')

Actually, my objective is to let the admin choose only from a specific model. So a solution that implements it there would be even better.

Thanks!

Henrik Andersson
  • 45,354
  • 16
  • 98
  • 92
Racing Tadpole
  • 4,270
  • 6
  • 37
  • 56
  • Do you mean that the content_type field should point to a model in a different app? – bozdoz Jun 13 '13 at 04:58
  • Also, have you tried it? Or are you just asking preemptively? – bozdoz Jun 13 '13 at 05:08
  • 1st q - I'm following the approach described in this [SO post](http://stackoverflow.com/questions/6335986/how-can-i-restrict-djangos-genericforeignkey-to-a-list-of-models). If there's a better way, please let me know! 2nd q - No, it doesn't work for me. Further, even if I define `content_type` with a `limit_choices_to` argument, `my_carousel.models.MyCarousel.content_type` has no attribute `limit_choices_to`. – Racing Tadpole Jun 13 '13 at 05:23
  • It's surprising how old that question is. The solution seemed to work for the OP, so to answer your question "Can this be done": yes. You *need* to share more of your app/model info, and what you've tried in order to figure out the problem. Did you try looping over `Contenttype.objects.all()` as suggested in your linked post's answer? – bozdoz Jun 13 '13 at 06:18

0 Answers0