Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django foreignkey get_or_create

Trying to check and see if a artist exists, if not add or link to foreignkey and save.

Here are the models

class Artist(models.Model):
    """Artist model"""
    title = models.CharField(max_length=250, unique=True)
    slug = models.SlugField(unique=True)


class Track(models.Model):
    """Track model"""
    artist = models.ForeignKey(Artist)
    title = models.CharField(max_length=250)
    slug = models.SlugField(unique=True)

Here is the script that checks

artist_id, created = Track.objects.get_or_create(artist_id=artist.title)
try:
    artist_title = artist_id.artist_set.all()
except IndexError:
    artist_slug = slugify(artist_title)
    try:
        artist = Artist.objects.create(title=artist_title, slug=artist_slug)
        # artist.add(artist_id)
        artist.save()

What am I doing wrong?

like image 979
tim Avatar asked Feb 10 '11 21:02

tim


1 Answers

For this example, accessing the get_or_create will not work when referencing a foreign key. This example makes it work:

a = Artist.objects.create(title='Sinch', slug='sinch')
t = Track.objects.create(artist=a, title='bitmap', slug='bitmap')
Track.objects.get_or_create(artist__id=1)
(<Track: Track object>, False) #is returned.

If you are trying to collect a track via the id of artist. To work around this - do:

try:
    a = Artist.objects.get(id=2)
except DoesNotExist:
    artist_title = 'title'
    artist_slug = slugify(artist_title)
    artist = Artist.objects.create(title=artist_title, slug=artist_slug)
    artist.save()

t, c = Track.objects.get_or_create(artist=a)

I know this is probably not what your looking for - But if you tell me the workflow you wish to apply, I can post more applicable code.

like image 183
Glycerine Avatar answered Sep 28 '22 00:09

Glycerine