0

Person と Items の 2 つの django モデルを作成しました (これが私のコードの一部です)。

class Person(models.Model):
    """ Represent a person who has credentials. The person may have
    devices and/or accessories. """ 

    #basic information
    name = models.CharField(max_length=50, unique=True)

class Item(models.Model):
""" Represents a device or accessory. """  
    owner = models.ForeignKey(Person)

基本的には、複数のアイテムを所有できる可能性がある人が 1 人必要です。所有者がアイテムを持っているかどうかを確認できる必要があり、アイテムに現在所有者がいるかどうかも確認できる必要があります。外部キーであるため、変数の所有者を操作できません。それとも、私はこの問題を間違って解決していますか?

私がこれに間違ったアプローチをしている場合、アイテムと所有者のデータベースを保存できる必要があり、所有者には複数のアイテムがあり、誰がどのアイテムを持っているかを知ることができるはずです。

助けてください!

4

1 に答える 1

0

項目の前に Person を宣言する必要があると思います。また、ForeignKey の代わりにManyToMany関係を使用することもできます。

class Item(models.Model):
""" Represents a device or accessory. """  
    name = models.models.CharField(max_length=50)

class Person(models.Model):
""" Represent a person who has credentials. The person may have
    devices and/or accessories. """ 

    #basic information
    name = models.models.CharField(max_length=50)
    item = models.ManyToManyField(Item)

つまり、基本的には逆に行っていました。したがって、オブジェクト Item を作成します。

item = Item.objects.create(name='itemname')

そして、それを person オブジェクトに追加します:

person = Person.objects.get(name="the person's name")
person.add(item)
person.save

これはうまくいくはずです

于 2013-05-07T01:55:14.467 に答える