Dynamically limit the selection for Foreignkey in Django models based on a different foreign key in the same model

I have these models:

class UserProfile(models.Model):
    name = models.CharField(max_length=100)

class Dialog(models.Model):
    belong_to = models.ManyToManyField(UserProfile)

class Message(models.Model):
    # Dialog to which this message belongs
    part_of = models.ForeignKey(Dialog)

    # User who sends message
    sender = models.ForeignKey(UserProfile, related_name='sender')
    # User who receives message 
    receiver = models.ForeignKey(UserProfile, related_name='receiver')

What I want to do is limit the selection of the sender and receiver fields so that they can only be users who own the entire dialog. I tried this:

sender = models.ForeignKey(UserProfile,
                           related_name='sender',
                           limit_choices_to={'dialog':1})

which restricts the selection, but only for dialogue members with id = 1. I wonder if this can be done dynamically?

+4
source share
2 answers

I do not believe that there is any way to dynamically filter how you want using limit_choices_to, since you will not have access to the necessary objects to create such a request.

, , . - ...

class MessageForm(forms.ModelForm):
    class Meta:
        model = Message

    def __init__(self, *args, **kwargs):
        super(MessageForm, self).__init__(*args, **kwargs)

        if self.instance.part_of and self.instance.part_of.id:
            users = self.instance.part_of.belong_to.all()
            self.fields['sender'].queryset = users
            self.fields['receiver'].queryset = users

, limit_choices_to , .

Django limit_choices_to , ModelForm. {dialog: 1} , UserProfile.objects.filter(dialog=1) .

Django , UserProfile, . id 1, . , ... , 0 .

, limit_choices_to UserProfile. Message, , Dialog, ... , , .

ModelForm , , .

+4

Message Dialog, messages Dialog? Dialog. , - :

class Dialog(models.Model):
    messages = models.ManyToManyField(Message)
    sender = models.ForeignKey(UserProfile)
    receiver = models.ForeignKey(UserProfile)

class Message(models.Model):
    # Other fields

, .

0

All Articles