开发者

Django: One-to-many relationship update

开发者 https://www.devze.com 2023-02-17 15:23 出处:网络
I am not sure how to describe this properly. But my models look like these: class Post(models.Model): title = models.CharField(max_length=250)

I am not sure how to describe this properly. But my models look like these:

class Post(models.Model):
    title = models.CharField(max_length=250)
    body = models.TextField()
    published = models.DateTimeField(null=True, blank=True)
    updated = models.DateTimeField(null=True, blank=True)
    user = models.ForeignKey(User)

class Unread(models.Model):
    user = models.ForeignKey(User)
    post = models.ForeignKey(Post)

My problem is when I try to UPDATE the Unread Model. Lets say in my "userlist" I have user ids: [1,3,5]

My Unread model has:

ID   USER   POST
1    1      1  # will row will remain because userid 1 is found in "userlist"
2    2      1  # --- this row would be deleted because USER is not found in "userlist"
3    3      1  # wil开发者_如何学运维l also remain because userid 3 is found in "userlist"
4    5      1  # NEW RECORD added because 5 was in "userlist" but not in Unread

Note: ID is autoincrement.

Does Django have an "automatic" way of doing this? Or what is the "recommended" way of handling these types of scenario?

I have encountered this problem a few times before and I remember that the "laziest" way I handled this was to DELETE everything in the Unread model and then ADD everything from the "userlist".

Best Regards, W


http://docs.djangoproject.com/en/dev/ref/models/querysets/#in http://docs.djangoproject.com/en/dev/ref/models/querysets/#values-list

There might be a better way to acheive the behavior you are looking for, but here is one way to go about it with value_list and using the queryset api exclude:

user_list = [ 1, 3, 5]

# gets you a qs
rows_to_delete = Unread.objects.exclude(user__in=user_list)
rows_to_delete.all().delete()

# gets you a list
users_in_unread = Unread.objects.value_list('user', flat=True)
users_to_add = [ user for user in users_list if user not in users_in_unread ]


You can create a new object with the Model.object.create() function. I have a similar situation when I call a display on something. If that something doesn't yet exist I catch the exception, create the new object, and subsequently add the necessary new stuff to it. For example, I add the foreign key to the object that didn't yet exist a few moments ago (which I think is what you're asking?)

So, query for the row you're looking for, if you don't find the object then create it with unread_variable = Model.object.create() and then use unread_variable to add whatever you need to add to it, such as the User.

Here is a link to some django examples on the subject.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号