开发者

Using python properties in django models?

开发者 https://www.devze.com 2022-12-18 13:10 出处:网络
My problem relates to this question: Default ordering for m2m items by intermediate model field in Django

My problem relates to this question: Default ordering for m2m items by intermediate model field in Django

class Group(models.Model):
   name = models.CharField(max_length=128)
   _members = models.ManyToManyField(Person, through='Membership')
   @property
   def members(self):
       return self._members.order_by('membership__date_joined')

   def __unicode__(self):
       return self.name

I used the best answer's solution as you see here, however, it broke my model form that's based on the group model.

When I submit the form, I get _members is required in my model form's error list since the field is required and can no longer submit forms based on this model.

The best answer in the prior question suggests a way to mimic the behavior of the field using the property. How would I go about doing this to completely hide _members from the model form?

Thanks, Pet开发者_运维技巧e


If it's a one-off, you can exclude the _members field when you create the modelform:

class GroupForm(ModelForm):
    class Meta:
        model=Group
        exclude = {'_members',}

If you do this a lot, you might consider creating a subclass of ModelForm and override the init method to automatically exclude properties starting with an underscore.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号