Django模型覆盖保存方法

时间:2019-09-28 09:05:00

标签: django django-models

这是我的模特

class Mess(models.Model):
    alias = models.UUIDField(
        primary_key=True,
        default=uuid4,
        editable=False
    )
    name = models.CharField(max_length=50, null=False, blank=False)
    address = models.CharField(max_length=300)
    admin = models.OneToOneField(
        Person,
        on_delete=models.CASCADE,
        related_name='mess_admin'
    )
    members = models.ManyToManyField(
        Person,
        related_name='mess_members',
        blank=True,
    )

    def save(self, *arg, **kwargs):
        print(kwargs)

创建新的混乱时,我试图达到目标,members字段应使用admin填充。

您可能会注意到,members字段是ManyManyToManyField,我想每创建一个新的mess时,admin的{​​{1}}也将是一个{{1 }},默认为mess

我知道我可以用信号来实现它,但是我不想要它。我要实现覆盖members的方法。

我希望成员的默认值为admin。

Mess

但这不起作用!!!!

任何人都可以帮助实现这一目标吗?

1 个答案:

答案 0 :(得分:2)

如下更改您的save方法:

models.py

from django.db import models
from uuid import uuid4


class Person(models.Model):
    name = models.CharField(max_length=32)

    def __str__(self):
        return "<Person {}>".format(self.name)


class Mess(models.Model):
    alias = models.UUIDField(
        primary_key=True,
        default=uuid4,
        editable=False
    )
    name = models.CharField(max_length=50, null=False, blank=False)
    address = models.CharField(max_length=300)
    admin = models.OneToOneField(
        Person,
        on_delete=models.CASCADE,
        related_name='mess_admin'
    )
    members = models.ManyToManyField(
        Person,
        related_name='mess_members',
        blank=True,
    )

    def save(self, *args, **kwargs):
        if self.admin not in self.members.all():
            self.members.add(self.admin)
        super(Mess, self).save(*args, **kwargs)

测试:

from testapp.models import Person, Mess

p1 = Person.objects.create(name="person1")

p2 = Person.objects.create(name="person2")

m1 = Mess.objects.create(name="mess1", address="address1", admin=p1)

m1.members.all()  # Person1 was added on save
<QuerySet [<Person: <Person person1>>]>

p1.mess_members.all()
<QuerySet [<Mess: Mess object>]>