2011-02-10 5 views
7

아티스트가 있는지 확인하고, 외부 키에 추가하거나 링크하지 않는 경우 확인하고 저장하십시오.Django foreignkey get_or_create

여기에 모델 여기

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) 

내가 뭘 잘못

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() 

를 확인하는 스크립트입니다입니까?

+0

어떤 오류가 발생합니까? – Glycerine

+1

밑이 10 인 int()에 대한 리터럴이 잘못되었습니다. – tim

+0

cool -하지만 전체 추적이 있습니까? 줄 번호 등? 방금 코드를 실행하려고 시도했는데 검사하는 스크립트의 첫 번째 줄에 오류가 발생했습니다. '..._ or_create (artist_id = '...')'란 무엇입니까? 트랙에는 'artist_id'라는 필드가 없습니다. – Glycerine

답변

12

이 예에서는 외래 키를 참조 할 때 get_or_create에 액세스 할 수 없습니다. 이 예제는 작동한다 :

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. 

당신이 아티스트의 ID를 통해 트랙을 수집하려고합니다. 이 문제를 해결하기 위해 - 할 일 :

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) 

을 나는 이것이 당신이 찾고있는 것을 아마 알고 -하지만 당신은 나에게 당신이 적용하고자하는 워크 플로우를 말한다면, 나는 더 많은 적용 코드를 게시 할 수 있습니다.

관련 문제