Home > Mobile >  How Do I Add Multiple Objects Inside A Foreign key in Django
How Do I Add Multiple Objects Inside A Foreign key in Django

Time:09-10

How do I make my Django view create an author model as an instance, and then save multiple objects inside the foreign key?

I have tried making a author instance, and then setting the tiktok attribute of the author instance to a new tiktok model instance with the desc, likes, etc. This just updated the previous value, not appending a new tiktok object.

Models.py

from django.db import models

# Create your models here.
class TikTok(models.Model):
    slug = models.SlugField(max_length=300, null=True)
    desc = models.TextField(max_length=500, blank=True)
    likes = models.CharField(default=None, blank=True, max_length=100)
    shares = models.CharField(default=None, blank=True, max_length=100)
    comments = models.CharField(default=None, blank=True, max_length=100)
    plays = models.CharField(default=None, blank=True, max_length=100)
    videoUrl = models.CharField(default=None, blank=True, null=True, max_length=500)
    videoImg = models.CharField(default=None, blank=True, null=True, max_length=500)
    music = models.CharField(default=None, blank=True, null=True, max_length=500)

    def __str__(self):
        return self.desc

class Author(models.Model):
    userhandle = models.CharField(max_length=100, blank=True)
    email = models.CharField(max_length=150, null=True, blank=True)
    verified = models.BooleanField(null=True)
    followers = models.IntegerField(default=0)
    tiktoks = models.ForeignKey(TikTok, on_delete=models.CASCADE, null=True, blank=True)

    def __str__(self):
        return self.userhandle

And then create the instances in my views.

I want one author model, and many tiktoks associated with it.

This is what the output should look like:

{
   id: 1,
   userhandle: 'user'
   email: '[email protected]'
   verified: True
   tiktoks: [
      #multiple arrays of tiktoks
      {
         desc: 'desc1',
         likes: 40,
         ...
      }, 
      {
         desc: 'desc2',
         likes: 40,
         ...
      }
      ...
   ]
}

CodePudding user response:

You could do this by 3 ways

  1. Make TikTok field many to many
  2. Make Outer table to store the author and the tiktok FK
  3. Make tiktok field string and store the IDs like this 1,2,3

CodePudding user response:

First you'd change the tiktok field to this, or similar tiktoks = models.ManyToManyField(TikTok)

Super Basic View Using Form

def create_tiktok(request):
    if request.method == 'POST':
        authorObj = Author.objects.filter(pk=request.POST.get('pk')).first()
        if authorObj:
            form = TikTokForm(request.POST)
            if form.is_valid():
                o = form.save()
                authorObj.tiktoks.add(o)

Example Remove

# format: model.field.action(obj)

authorObj.tiktoks.remove(TikTok.objects.get(pk=1))

Example Usage

authorObj = Author.objects.get(userhandle='Nealium')

# Looping through all
for i in authorObj.tiktoks.all():
    print(i) # <TikTok Object>

# Fetching a specific
authorObj.tiktoks.filter(slug='test').first()


# Mass Adding
tiktokList = TikTok.objects.filter(slug__icontains='te')
authorObj.tiktoks.add(*tiktokList)


# Mass Remove
authorObj.tiktoks.add(*tiktokList)


# Clear entire field
authorObj.tiktoks.clear()
  • Related