English 中文(简体)
Django的许多原子领域的反证模型
原标题:Instantiate model instance with manytomany field in Django

我有一种行之有效的方法,但似乎很奇怪,我认为这样做有更好的办法。

我有一份模型,把我的网站上的用户(用于学习目的的tw带)与其他用户名单联系起来。

现在,在我创建新用户的时候,我希望把这份名单与用户一起作为名单的成员。

我的模式是:

class FollowerList(models.Model)
    follower = models.ForeignKey(User,related_name="follower")
    followed = models.ManyToManyField(User,related_name="followed")

我认为,现在使用的是Im。

user = User.objects.get(username=uname)
flst = FollowerList()
flst.follower = user
flst.save()
flst.followed.add(user)
flst.save()

在我看来,should 是创造这种机会的一种方法,而无需打上save(<>/code>两次,但我似乎无法在docs或其他任何地方找到。

最佳回答

你们不需要在很多2many.add()之后打电话。

您还可以将守则缩短为2行:

flst = FollowerList.objects.create(follower=user)
flst.followed.add(user)
问题回答

Yuji的答复是正确的。 在M2M油田被拯救之前,你不能再添加物体。 我想提一下的是,通过这种方式来制造一些例子。

user = User.objects.get(username=uname)
flst = FollowerList(follower=user) #use key word args to assign fields
flst.save()
flst.followed.add(user)
# don t need to save after adding an object to many to many field.

我发现,除制造空洞和分配田地外, s子稍有nic。 尽管物体(Yuki语)方法(Yuki语)仍然nic。

A 对这一的延迟答复:您也可超越构件(_init__):

class FollowerList(models.Model):
    follower = models.ForeignKey(User,related_name="follower")
    followed = models.ManyToManyField(User,related_name="followed"

    def __init__(*args, followed=[], **kwargs):
        super(FollowerList, self).__init__(*args, **kwargs)
        self.save()
        for user in followed:
            self.followed.add(user)

ie here I ve explicitly handled the followed keyword argument in the __init__ function, while passing all other args and kwargs on to the default constructor. The call to save makes sure that the object has been registered and can thus be used in an m2m relationship.

This then allows you to do create FollowerList with one line, eg

flst = FollowerList(follower=user, followed=[user,])

Alternatively, as pointed out by Johannes, saving a model in the __init__ is not expected. The preferred approach would be to create a Manager method - see here for details: https://docs.djangoproject.com/en/1.9/topics/db/managers/ and then to create a FollowerList:

fl = FollowerList.objects.create(*args, followed, **kwargs)




相关问题
How to get two random records with Django

How do I get two distinct random records using Django? I ve seen questions about how to get one but I need to get two random records and they must differ.

Moving (very old) Zope/Plone Site to Django

I am ask to move data from a (now offline) site driven by Plone to a new Django site. These are the version informations I have: Zope Version (unreleased version, python 2.1.3 ) Python Version 2.1....

Can Django models use MySQL functions?

Is there a way to force Django models to pass a field to a MySQL function every time the model data is read or loaded? To clarify what I mean in SQL, I want the Django model to produce something like ...

Flexible pagination in Django

I d like to implement pagination such that I can allow the user to choose the number of records per page such as 10, 25, 50 etc. How should I go about this? Is there an app I can add onto my project ...

is it convenient to urlencode all next parameters? - django

While writing code, it is pretty common to request a page with an appended "next" query string argument. For instance, in the following template code next points back to the page the user is on: &...

Pragmatically adding give-aways/freebies to an online store

Our business currently has an online store and recently we ve been offering free specials to our customers. Right now, we simply display the special and give the buyer a notice stating we will add the ...