在Django中自动生成一组通用的许多字段? [英] Autopopulate a set of generic many to many fields in Django?

查看:125
本文介绍了在Django中自动生成一组通用的许多字段?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试将答案与此一个,有点循环。

I'm trying to combine this answer and this one, with a bit of for looping.

在创建一个字符时,我想添加所有可能的技能值的0,但我对如何遵循上述答案感到困惑。

On creating a character, I want to add all possible skills with a value of 0 but I'm getting confused on how to follow the above answers.

我有这个mixin:

class CrossCharacterMixin(models.Model):
    cross_character_types = models.Q(app_label='mage', model='mage')
    content_type = models.ForeignKey(ContentType, limit_choices_to=cross_character_types,
                                     null=True, blank=True)
    object_id = models.PositiveIntegerField(null=True)
    content_object = GenericForeignKey('content_type', 'object_id')

    class Meta:
        abstract = True

cross_character_types 将是ex panded)

(eventually, the cross_character_types will be expanded)

此模型:

class CharacterSkillLink(Trait, CrossCharacterMixin):
    PRIORITY_CHOICES = (
        (1, 'Primary'), (2, 'Secondary'), (3, 'Tertiary')
    )
    skill = models.ForeignKey('SkillAbility')
    priority = models.PositiveSmallIntegerField(
        choices=PRIORITY_CHOICES, default=None)
    speciality = models.CharField(max_length=200, null=True, blank=True)

    def __str__(self):
        spec_string = " (" + self.speciality + ")" if self.speciality else ""
        return self.skill.skill.label + spec_string

我开始写的是这个,在NWODCharacter模型中: / p>

What I've started writing is this, on the NWODCharacter model:

def save(self, *args, **kwargs):
    if not self.pk:
        character_skills_through = CharacterSkillLink.content_object.model

        CharacterSkillLink.objects.bulk_create([
            [character_skills_through(skill=SkillAbility(
                skill), content_object=self) for skill in SkillAbility.Skills]
        ])

    super(NWODCharacter, self).save(*args, **kwargs)

这不工作,因为我不认为我传入正确的对象。

This doesn't work as I don't think I'm passing in the right objects.

根据此答案: / p>

Based on this answer though:


from django.db import models

class Users(models.Model):
    pass

class Sample(models.Model):
    users = models.ManyToManyField(Users)

Users().save()
Users().save()

# Access the through model directly
ThroughModel = Sample.users.through

users = Users.objects.filter(pk__in=[1,2])

sample_object = Sample()
sample_object.save()

ThroughModel.objects.bulk_create([
    ThroughModel(users_id=users[0].pk, sample_id=sample_object.pk),
    ThroughModel(users_id=users[1].pk, sample_id=sample_object.pk)
])


在这种情况下,我的 ThroughModel 是什么?是否 CharacterSkillLink.content_object.model

In this situation, what is my ThroughModel? Is it CharacterSkillLink.content_object.model ?

如何在我的场景中执行此操作?我很抱歉,如果这是微不足道的,但我正在努力让我的头脑圆满。

How do I do this in my scenario? I'm sorry if this is trivial, but I'm struggling to get my head round it.

推荐答案

它看起来像我像 CharacterSkillLink 本身就是您在这种情况下的直通模式...它通常将内容类型加入到一个 SkillAbility

It looks to me like CharacterSkillLink itself is your through model in this case... it generically joins a content type to a SkillAbility

如果你想到这一点,那么如果你正在做一个 bulk_create 你传入的对象也是有道理的必须是相同的型号,你正在做一个 bulk_create

If you think about it, it also makes sense that if you're doing a bulk_create the objects that you pass in must be of the same model you're doing a bulk_create on.

所以我想你想要这样的东西:
$ b

So I think you want something like this:

def save(self, *args, **kwargs):
    initialise_skill_links = not self.pk
    super(NWODCharacter, self).save(*args, **kwargs)
    if initialise_skill_links:
        CharacterSkillLink.objects.bulk_create([
            CharacterSkillLink(
                skill=SkillAbility.objects.get_or_create(skill=skill)[0],
                content_object=self
            )
            for skill in SkillAbility.Skills
        ])

请注意,您有太多的<$您的 bulk_create 中的c $ c> [] 。

Note you had too many pairs of [] inside your bulk_create.

使用 SkillAbility.objects.get_or_create() ...对于外键,您需要相关对象存在。只要做 SkillAbility()将不会从数据库中获取它,如果它已经存在,并且不会将其保存到数据库(如果没有)。

Also I think you should use SkillAbility.objects.get_or_create()... for a foreign key you need the related object to exist. Just doing SkillAbility() won't fetch it from the db if it already exists and won't save it to the db if it doesn't.

这篇关于在Django中自动生成一组通用的许多字段?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆