N
N
Nikita Roschenko2015-08-26 20:13:16
Django
Nikita Roschenko, 2015-08-26 20:13:16

How to correctly compose limit_choices_to?

Good afternoon, there is a user profile in the admin panel, he has a set of photos, and some of these photos can be set as a profile photo. But with the current implementation in select'e a list of all photos in the system is displayed, not limited to the edited profile. So I wanted to limit the profile photo selection select to the current profile being edited, but I don't know how.
I have 3 models:

class Account(models.Model):
    login = models.CharField(max_length=255)
    password = models.CharField(max_length=255)
    first_name = models.CharField(max_length=255)
    last_name = models.CharField(max_length=255)


class Photo(models.Model):
    account = models.ForeignKey(Account)
    photo_name = models.CharField(max_length=255)

class ProfilePhoto(models.Model):
    account = models.ForeignKey(Account)
    photo = models.ForeignKey(Photo, limit_choices_to=Q(account__id=account.primary_key))

When outputting selecta to select a profile photo, the following query is generated in mysql:
SELECT `clones_photo`.`id`,  `clones_photo`.`account_id`,  `clones_photo`.`photo_name`  FROM `clones_photo` WHERE `clones_photo`.`account_id` = 0

That is, there is an Account model, this model has associated Photo models. And I need to limit the selection in the ProfilePhoto model to only those Photo models that are associated with the current Account model. But instead of Account.id, 0 is substituted.
How to do it right?

Answer the question

In order to leave comments, you need to log in

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question