Django filter form field objects by existing one-to-one relation

Viewed 300

I'm new to django and still trying to figure out basic things. I have three models: pc, pcslot and card. pcslot contains the relations to slots and to pc. One pc can have multiple slots, each card can only be in one slot.

class pcslot(models.Model):
    card = models.OneToOneField("card
        on_delete=models.SET_NULL,
        null=True,
        blank=True
    )
    computer = models.ForeignKey('pc',
        on_delete=models.CASCADE, 
        related_name='slots',
        editable=False
    )

Now I would like to exclude all already assigned cards from the form dropdown. I tried to filter the objects inside the form by adding this to the model

def get_related(self):
   if(hasattr(self, 'pcslot')):
       return 1
   return None

But django object filter cannot access these methods, so filter(get_related=1) is not working:

class pcslotForm(ModelForm): class Meta: model = pcslot fields = "all" def init(self, user=None, **kwargs): super(pcslotForm, self).init(**kwargs) self.fields['card'].queryset = card.objects.filter(get_related=1)

What would be the best way to do this? Do I have to loop through all objects and compare or is there a builtin method I don't know yet? Thanks

1 Answers

Now I would like to exclude all already assigned cards from the form dropdown.

I'm assuming from this you want a queryset of all cards that aren't on the far side of a pcslot.card relationship. If so, then you can just use a relational field in your filter. So

cards_without_assigned_slots = card.objects.filter(pcslot__isnull=True)

Note, it's more pythonic to name your classes with CamelCase (so Card instead of card)

Related