CodeSpent
CodeSpent

Reputation: 1904

OneToMany on existing object Django

I'm experimenting to get a better idea of how Django works. Take the below test function that creates a Category, Tag, and Item representing Macbook Pros then adds a Macbook Pro to that Category, Tag, and Item (product).

Relevant Models: (Note I am in the middle of troubleshooting, models may not exactly represent what they were at the time of the question)

class Tag(models.Model):
    title = models.CharField(max_length=20)

    def __str__(self):
        return self.title

class Item(models.Model):
    name = models.CharField(max_length=100)
    description = models.CharField(max_length=100)
    manufacturer = models.ForeignKey('Manufacturer', blank=True, null=True, on_delete=models.SET_NULL)
    introduction = models.DateField(auto_now=True)
    quanity = models.IntegerField(default=0)
    is_retired = models.BooleanField(default=False)
    tags = models.ManyToManyField(Tag)

    def __str__(self):
        return self.name

    def add(self):
        pass

    def remove(self):
        pass

    def retire(self): # Rex came up with this, roll credits.
        pass 

    def count(self):
        pass

class OnHand(models.Model):
    name = models.CharField(max_length=100)
    serial = models.CharField(max_length=80)
    asset = models.CharField(max_length=20)
    product = models.ForeignKey(Item, blank=True, null=True, on_delete=models.CASCADE)


    def __str__(self):
        return self.serial

Test Cases:

def make_macbook():
    """ Create a Manufacturer for Apple """
    apple = Manufacturer(name='Apple', rep_name='Jason Wilburn', support_number='1-800-Apple')
    apple.save()
    print('Manufacturer name: {}'.format(apple))

    """ Create a Category for Laptops """
    laptop = Category(name='Laptops')
    laptop.save()
    print('Category name: {}'.format(laptop))

    """ Create a Tag for Mac """
    mac = Tag(title='mac')
    mac.save()
    print('Tag name: {}'.format(mac))

    """ Create a MacBook Item """
    macbook = Item(name='Macbook Pro', description='15.5" Macbook Pro, 2018 Model', manufacturer=apple)
    macbook.save()
    print('Item name: {}'.format(macbook))

    """ Create a MacBook OnHand item """
    newMac = OnHand(name='MacBook Pro 15.5"', serial='SC02XP0NRJGH5', asset='DEPSC02XP0NRJGH5', product=macbook)
    newMac.save()


    return newMac.product

What I'm testing now is adding new OnHand objects to the Category, Tag, and Item.

Here is what I have:

def add_macbook():
    """ Find MacBook Item """
    macbook = Item.objects.filter(name='Macbook Pro')

    """ Create a MacBook OnHand item """
    newMac = OnHand(name='MacBook Pro 15.5"', serial='000000000000000', asset='DEP0000000000000', product=macbook)
    newMac.save()

I'm confronted with 2 problems:

  1. Class 'Item' has no 'objects' member
  2. ValueError: Cannot assign "]>": "OnHand.product" must be a "Item" instance.

How would I get an existing Item instance to associate?

I have also tried:

def add_macbook():
    """ Find MacBook Item """
    macbook = Item.objects.get(name='Macbook Pro')

    """ Create a MacBook OnHand item """
    newMac = OnHand(name='MacBook Pro 15.5"', serial='000000000000000', asset='DEP0000000000000')
    newMac.save()
    macbook.product.add(newMac)

Which presents me with the obvious 'Item' has no attribute 'product' because it obviously doesn't. I tried this because of how my Tag model works.

Upvotes: 0

Views: 107

Answers (1)

c6754
c6754

Reputation: 887

The .filter() function returns a queryset rather than a single model instance and you can't assign an entire queryset as a foreign key. On the other hand .get() will return a single model instance. You almost had the right combination. Try this:

def add_macbook():
    """ Find MacBook Item """
    macbook = Item.objects.get(name='Macbook Pro')


    """ Create a MacBook OnHand item """
    newMac = OnHand(
        name='MacBook Pro 15.5"',
        serial='000000000000000',
        asset='DEP0000000000000',
        product=macbook
    )
    newMac.save()

That Class 'Item' has no 'objects' member error doesn't make sense to me. Is it maybe just an IDE warning?

Here is the link for the filter function.

Upvotes: 2

Related Questions